I have a sequential process with an optional exit condition. One way to write the algorithms is like this
let mutable more = true
for slot = startSlot to endSlot do
if more then
more <- process()
The overhead of checking more
for slots that are skipped due to an exit is insignificant. Still, it seems there should be a more elegant way to express this.
To stop the while loop you need to make sure that none of the conditions are met, else it will keep running. By changing || to && you are saying that both conditions need to be met in order to continue looping. Alternatively, you can use your orginal code but replace break with c = -1.
Using break , you can come out of the loop even if the condition for the end of the loop is not fulfilled. You cant have break because 'if /elif ' is not a loop, its just a conditional statement.
break labelname; continue labelname; The continue statement (with or without a label reference) can only be used to skip one loop iteration. The break statement, without a label reference, can only be used to jump out of a loop or a switch.
Recursion is usual here:
let rec loop slot = if slot <= endSlot && process () then loop (slot + 1)
loop startSlot
The compiler will reduce this to a simple loop (no actual recursion takes place).
One way of doing this would be to use Seq.takeWhile
seq{startSlot .. endSlot}
|> Seq.takeWhile (fun _ -> process())
|> Seq.iter ignore
This will exit the loop when process()
returns false
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