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; }
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.
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. :-(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With