Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }  
like image 917
cheziHoyzer Avatar asked May 14 '13 12:05

cheziHoyzer


2 Answers

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.

like image 63
Tomas Petricek Avatar answered Sep 20 '22 13:09

Tomas Petricek


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. :-(

like image 42
itmuckel Avatar answered Sep 19 '22 13:09

itmuckel