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





