seq<'T> (an alias for IEnumerable<'T>) is lazy: items are computed as they're pulled.
F# Easy · Lesson 1 · On the house
Sequences and laziness
seq expressions, Seq module, infinite sequences, and caching. Lesson 1 is free — on the house.
Lessons · F# Easy · Lesson 1 of 10 · On the house
Sequences and laziness
seq expressions, Seq module, infinite sequences, and caching.

Sequence expressions: seq { for i in 1 .. 3 do yield i * i }; yield! splices another sequence in.
Infinite sequences are fine if you limit them: Seq.initInfinite id |> Seq.take 5.
A seq re-runs its work each time it's enumerated. Seq.cache memoizes, or materialize with Seq.toList.
Use List when you need the whole collection now, Seq for streaming or large/infinite data.
seq
let squares = seq { for i in 1 .. 5 do yield i * i }
printfn "%A" (Seq.toList squares)
let naturals = Seq.initInfinite (fun i -> i + 1)
naturals |> Seq.filter (fun n -> n % 7 = 0) |> Seq.take 3 |> Seq.toList |> printfn "%A"
let mutable runs = 0
let noisy = seq { runs <- runs + 1; yield 1; yield 2 }
noisy |> Seq.sum |> ignore
noisy |> Seq.sum |> ignore
printfn "runs=%d" runs
let cached = Seq.cache noisy
cached |> Seq.sum |> ignore
cached |> Seq.sum |> ignore
printfn "runs=%d" runs
let both = seq { yield 0; yield! [1; 2] }
printfn "%A" (List.ofSeq both)
Quiz
Quiz
Quiz
Quiz
Check
Match the still for: Sequences and laziness.
Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.