liveBook · Manning

Comprehension

As explained in F# in Action: A Revised Edition of Get Programming with F#

A collection comprehension is syntax for constructing a collection from generator, filtering, and transformation logic.

A comprehension constructs a collection from executable logic. In F#, sequence comprehensions can emit values, branch with if/then, call functions, and run nested or external computations. They replace much of the boilerplate needed to generate collections imperatively. section 7.3.8 section 7.6

Conditionally adding a value

The following sequence emits 1, 2, and 4, adding 99 only on Tuesday: let comp = seq { 1 2 if DateTime.Today.DayOfWeek = DayOfWeek.Tuesday then 99 4 } Modern F# lets the expression stand alone; older code required yield 99. The yield! keyword remains useful for unwrapping nested lists inside a comprehension. section 7.3.8

Comprehensions are especially useful when imperative-looking sources should become ordinary sequences. Generate dates with a loop, filter them with Seq operations, or expose console input as a string sequence that can be tested independently of the console. section 7.4.3 section 10.1.1

Use comprehensions to:

  • Generate streams such as dates or repeated console input. section 7.4.3
  • Feed generated values into filtering, choosing, folding, and other sequence pipelines. section 10.1.1
  • Create domain-specific languages from expressions and conditional logic, while reserving ordinary loops for pipeline side effects or collection generation. section 7.3.8 section 7.4.1
Listing 7.11 Creating a Sequence comprehension
let comp = seq {
    1                                                          #1
    2
    if DateTime.Today.DayOfWeek = DayOfWeek.Tuesday then 99    #2
    4
}

Inspect a minimal sequence comprehension with unconditional values and a conditional value. section 7.3.8

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Explains syntax, conditional emission, yield versus yield!, generated streams, and pipeline use, but does not develop formal semantics.
Examples
Demonstrates conditional sequence values, date streams, Monday selection, console commands, and event-driven input pipelines.
What it assumes
Assumes basic F# expressions and collections while showing how loops, conditionals, and external inputs become sequences.
What you can do after
Build it from scratch using sequence comprehensions, then apply standard sequence operations to generated dates, console input, or event data.
How it connects
Connects comprehensions with sequences, lazy evaluation, filtering, pipelines, imperative loops, domain-specific languages, and event streams.

Also explained in

Compare how 6 books explain comprehension →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.