typestar

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

  1. Seq.initInfinite defines every brood cycle at once.
  2. skip and take decide how much actually computes.
  3. Seq.unfold grows from state until None says stop.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Signatures & laziness, step 24 of 27 in Language basics.

← Previous Next →