Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean functional way to break out of a sequence loop

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.

like image 513
Edward Brey Avatar asked Feb 20 '17 14:02

Edward Brey


People also ask

How to break a while loop without using break?

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.

Can you break a loop inside a function?

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.

Can we use break without loop?

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.


2 Answers

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).

like image 144
ildjarn Avatar answered Oct 13 '22 19:10

ildjarn


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

like image 24
klasske Avatar answered Oct 13 '22 19:10

klasske