Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Collections and Sequences

F# Sequences: Lazy seq Expressions, Infinite Data and the Seq Module

Understand F# sequences: lazy evaluation, seq expressions with yield, infinite sequences with Seq.initInfinite and unfold, caching, the Seq module, and when to choose seq over list or array.

A sequence (seq<'T>, the same as .NET's IEnumerable<'T>) is a collection that produces its items on demand. Nothing is computed until something asks for the next value. That laziness lets you work with huge files, expensive computations and even infinite streams, using exactly the same pipeline style as lists. This lesson explains laziness, seq expressions, infinite sequences, and the pitfalls (re-evaluation and deferred side effects).

Lazy versus eager

A list or array holds all its items in memory the moment it exists. A sequence holds only the recipe:

FSHARP
let eager =
    [ for i in 1 .. 3 do
        printfn "list item %d" i
        yield i ]
// prints three lines immediately

let lazyOne =
    seq { for i in 1 .. 3 do
            printfn "seq item %d" i
            yield i }
// prints nothing yet

Only when you consume lazyOne does the work happen:

FSHARP
let first = lazyOne |> Seq.head        // prints "seq item 1" only, returns 1

The other two items are never computed. That is lazy evaluation, and it is the superpower of seq.

flowchart LR
    A["source"] --> B["Seq.filter"] --> C["Seq.map"] --> D["Seq.take 3"]
    D --> E["consumer pulls items one by one"]

Items flow through the pipeline one at a time as the consumer asks for them; no intermediate lists are built.

Creating sequences

FSHARP
let s1 = seq { 1 .. 5 }                    // range
let s2 = seq { 1; 2; 3 }                   // explicit items
let s3 = Seq.ofList [ 1; 2; 3 ]            // from a list
let s4 = Seq.init 5 (fun i -> i * i)       // 0 1 4 9 16
let s5 = seq { for i in 1 .. 10 do if i % 2 = 0 then yield i }
let s6 = Seq.replicate 3 "ha"

Lists, arrays, strings, Maps and Sets are all sequences too, so every Seq function works on them.

seq expressions

Inside seq { ... } you write ordinary-looking code and yield items:

FSHARP
let evensTo n =
    seq {
        for i in 1 .. n do
            if i % 2 = 0 then
                yield i
    }

let withExtras =
    seq {
        yield 0
        yield! evensTo 6        // yield! inserts a whole sequence
        yield 100
    }
// 0, 2, 4, 6, 100

yield! ("yield bang") splices another sequence in place. The -> arrow is shorthand for do yield in a one-expression for. In recent F# versions you can drop the yield keyword entirely when the meaning is clear (seq { 1; 2; 3 }), as in the examples above.

Infinite sequences

Since items are produced on demand, a sequence may never end:

FSHARP
let naturals = Seq.initInfinite id               // 0, 1, 2, 3, ...
let powersOfTwo = Seq.initInfinite (fun i -> pown 2 i)

powersOfTwo |> Seq.take 5 |> Seq.toList          // [1; 2; 4; 8; 16]

Seq.unfold generates a sequence from a state: the function returns Some (item, nextState) to continue or None to stop.

FSHARP
let fibs =
    Seq.unfold (fun (a, b) -> Some (a, (b, a + b))) (0, 1)

fibs |> Seq.take 8 |> Seq.toList          // [0; 1; 1; 2; 3; 5; 8; 13]

Always limit an infinite sequence with Seq.take, Seq.takeWhile or Seq.truncate before turning it into a list; Seq.toList on an infinite sequence never finishes.

The Seq module

Seq mirrors List and Array: map, filter, fold, sum, length, exists, tryFind, sortBy, groupBy, distinct, zip, collect, windowed, pairwise and more. Notable lazy-specific ones:

FSHARP
Seq.initInfinite id
|> Seq.filter (fun n -> n % 7 = 0)
|> Seq.skip 1
|> Seq.truncate 3
|> Seq.toList
// [7; 14; 21]
Function Meaning
Seq.take n first n items (throws if too few)
Seq.truncate n up to n items, no error
Seq.takeWhile p items while predicate holds
Seq.skipWhile p drop leading matching items
Seq.cache remember computed items
Seq.toList, Seq.toArray force evaluation
Seq.iter run an action for each item (forces it)
Seq.readonly hide the underlying collection type

Functions like Seq.sort, Seq.groupBy and Seq.length must read the whole sequence, so they are not lazy end to end.

Pitfall 1: re-evaluation

A sequence is a recipe, so each consumption runs it again:

FSHARP
let expensive =
    seq {
        printfn "computing..."
        yield 1
        yield 2
    }

expensive |> Seq.sum |> ignore      // prints "computing..."
expensive |> Seq.length |> ignore   // prints "computing..." again

If the work is costly, either materialise once (Seq.toList, Seq.toArray) or wrap with Seq.cache.

Pitfall 2: deferred side effects and resources

Code that reads a file or database lazily might run after the file is closed:

FSHARP
let lines =
    use reader = new System.IO.StreamReader "data.txt"
    seq {
        while not reader.EndOfStream do
            yield reader.ReadLine()
    }

The use ends when lines is defined, before anyone reads it, so reading later fails. Put the use inside the seq { ... }, or use System.IO.File.ReadLines "data.txt", which is lazy and manages its own handle.

Choosing a collection

Situation Pick
Small data, pattern matching, immutability list
Big numeric data, speed, interop array
Huge, streamed or infinite data; pipelines over IO seq
Need to read it several times list or array (or Seq.cache)

C# stand-ins: IEnumerable and yield

C#'s IEnumerable<T> with yield return is the same mechanism. The first stand-in builds Fibonacci as an infinite lazy sequence; the second shows deferred execution and re-evaluation.

C# C# stand-in: an infinite lazy sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# C# stand-in: deferred execution runs again

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main difference between a seq and a list?

    Sequences are recipes evaluated when consumed, so they can be huge or infinite.
  2. 2. What does yield! do inside a seq expression?

    yield! splices a whole sequence into the result.
  3. 3. What happens with Seq.initInfinite id |> Seq.toList?

    toList must consume everything. Limit the sequence first with take, truncate or takeWhile.
  4. 4. How can you avoid re-running an expensive sequence several times?

    Materialising with toList/toArray or caching stores the computed items.

Summary

  • seq<'T> is lazy: items are computed when consumed, so memory stays small and infinite data is possible.
  • Build sequences with seq { ... }, yield, yield!, Seq.init, Seq.initInfinite and Seq.unfold.
  • The Seq module mirrors List; use take, truncate and takeWhile to limit infinite data.
  • Each consumption re-runs the recipe; use Seq.cache or materialise when needed.
  • Keep resources (use) inside the seq expression for lazy file or database reads.

Next: Maps and sets