F# break from while loop

后端 未结 7 2103
甜味超标
甜味超标 2021-02-18 14:30

There is any way to do it like C/C#?

For example (C# style)

for (int i = 0; i < 100; i++)
{
   if (I == 66)
       break;
} 
7条回答
  •  余生分开走
    2021-02-18 15:15

    Try this:

    exception BreakException
    
    try
        for i = 0 to 99 do
          if i = 66 then
            raise BreakException
    with BreakException -> ()
    

    I know that some folks don't like to use exceptions. But it has merits.

    • You don't have to think about complicated recursive function. Of cause you can do that, but sometimes it is unnecessarily bothersome and using exception is simpler.

    • This method allows you to break at halfway of the loop body. (Break "flag" method is simple too but it only allows to break at the end of the loop body.)

    • You can easily escape from nested loop.

提交回复
热议问题