Clear functional way to exit sequence loop

I have a sequential process with an additional exit condition. One way to write algorithms:

let mutable more = true for slot = startSlot to endSlot do if more then more <- process() 

The overhead of checking more for slots skipped due to exit is not significant. However, there seems to be a more elegant way of expressing this.

+5
source share
2 answers

Recursion is usually used here:

 let rec loop slot = if slot <= endSlot && process () then loop (slot + 1) loop startSlot 

The compiler will reduce this to a simple loop (the actual recursion fails).

+9
source

One way to do this is to use Seq.takeWhile

 seq{startSlot .. endSlot} |> Seq.takeWhile (fun _ -> process()) |> Seq.iter ignore 

This will exit the loop when process() returns false

+4
source

Source: https://habr.com/ru/post/1264456/


All Articles