Lazy sequences in F#
Infinite is fine until something pulls.
// Sequences are lazy: infinite is fine until something pulls.
let broodCycles = Seq.initInfinite (fun day -> day * 21)
broodCycles
|> Seq.skip 1
|> Seq.take 4
|> Seq.iter (printfn "New workers on day %d")
// unfold grows a sequence from state until None says stop.
let syrup = Seq.unfold (fun left ->
if left <= 0.0 then None
else Some (left, left - 2.5)) 10.0
printfn "Feedings: %A" (syrup |> Seq.toList)
How it works
Seq.initInfinitedefines every brood cycle at once.skipandtakedecide how much actually computes.Seq.unfoldgrows from state until None says stop.
Keywords and builtins used here
elsefunifletthen
The run, in numbers
- Lines
- 13
- Characters to type
- 408
- Tokens
- 86
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 86 seconds.
Step 3 of 3 in Signatures & laziness, step 24 of 27 in Language basics.