Search code examples
f#while-loopbreak

F# break from while loop


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;
} 

Solution

  • The short answer is no. You would generally use some higher-order function to express the same functionality. There is a number of functions that let you do this, corresponding to different patterns (so if you describe what exactly you need, someone might give you a better answer).

    For example, tryFind function returns the first value from a sequence for which a given predicate returns true, which lets you write something like this:

    seq { 0 .. 100 } |> Seq.tryFind (fun i ->
      printfn "%d" i
      i=66)
    

    In practice, this is the best way to go if you are expressing some high-level logic and there is a corresponding function. If you really need to express something like break, you can use a recursive function:

    let rec loop n = 
      if n < 66 then 
        printfn "%d" n
        loop (n + 1)
    
    loop 0      
    

    A more exotic option (that is not as efficient, but may be nice for DSLs) is that you can define a computation expression that lets you write break and continue. Here is an example, but as I said, this is not as efficient.