F# break from while loop

This is really ugly, but in my case it worked.

let mutable Break = false
while not Break do
    //doStuff

    if breakCondition then
        Break <- true
done

This is useful for do-while loops, because it guarantees that the loop is executed at least once.

I hope there's a more elegant solution. I don't like the recursive one, because I'm afraid of stack overflows. :-(


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.