Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Collections and Sequences

F# List Comprehensions and Choosing Collection Functions

Build collections with F# list, array and seq comprehensions, use yield and yield!, nested for loops and guards, then learn which collection function to choose for each task with worked examples.

You now know three collections (list, array, seq), a map and a set. This closing lesson of the chapter does two things. First, it shows comprehensions, the declarative way to build any of them with for, if and yield. Second, it gives you a decision guide to the huge List/Array/Seq function families so you pick the right one without searching, and finishes with a worked example that combines everything.

Comprehensions

A comprehension is a block of code that generates the elements. The brackets decide the collection:

FSHARP
let squaresList = [ for i in 1 .. 5 -> i * i ]           // list
let squaresArray = [| for i in 1 .. 5 -> i * i |]        // array
let squaresSeq = seq { for i in 1 .. 5 -> i * i }        // lazy seq

The arrow -> means "yield this value". For anything more complex, use do and yield:

FSHARP
let evenSquares =
    [ for i in 1 .. 10 do
        if i % 2 = 0 then
            yield i * i ]
// [4; 16; 36; 64; 100]

The if without else works because a comprehension that does not yield simply skips the iteration. That is a guard, the same as List.filter and List.map combined.

Nested loops

Multiple for clauses produce combinations:

FSHARP
let pairs =
    [ for x in 1 .. 3 do
        for y in 1 .. 3 do
            if x < y then
                yield (x, y) ]
// [(1, 2); (1, 3); (2, 3)]

Pythagorean triples with a bound:

FSHARP
let triples =
    [ for a in 1 .. 20 do
        for b in a .. 20 do
            for c in b .. 20 do
                if a * a + b * b = c * c then
                    yield (a, b, c) ]
// [(3, 4, 5); (5, 12, 13); (6, 8, 10); (8, 15, 17); (9, 12, 15); (12, 16, 20)]

yield!, let and match inside comprehensions

yield! splices a whole collection. Local let bindings and match are allowed too:

FSHARP
let describe n =
    [ for i in 1 .. n do
        let isEven = i % 2 = 0
        match isEven with
        | true -> yield $"{i} even"
        | false -> () ]

let combined = [ yield 0; yield! [ 1; 2 ]; yield 3 ]     // [0; 1; 2; 3]

Branches that yield nothing return (), the unit value (Tuples and unit).

Comprehension or pipeline?

Both are fine, and they are often equivalent:

FSHARP
[ for n in numbers do if n > 0 then yield n * 2 ]
numbers |> List.filter (fun n -> n > 0) |> List.map (fun n -> n * 2)

Choose a comprehension when you have several loops, local variables or conditionals to combine; choose a pipeline for simple transformations of an existing collection.

Decision guide: which function?

I want to... Use
change every item map
change every item and know its index mapi
keep some items filter
map and drop failures in one step choose (returns Some/None)
flatten nested collections concat (or collect = map + concat)
combine all items into one value fold (or reduce if never empty)
sum, min, max of a field sumBy, minBy, maxBy
count by key countBy
group by key groupBy
find the first match tryFind (safe) / find (throws)
find a position tryFindIndex
test a condition exists, forall, contains
split in two partition
sort sort, sortBy, sortWith, sortDescending
remove duplicates distinct, distinctBy
join two collections item by item zip, map2
slices take, skip, truncate, chunkBySize, windowed
run side effects iter, iteri
lazy and possibly infinite Seq.*

choose deserves a special mention. It combines map and filter when the mapping can fail:

FSHARP
let parse (s: string) =
    match System.Int32.TryParse s with
    | true, n -> Some n
    | _ -> None

[ "1"; "x"; "3" ] |> List.choose parse        // [1; 3]

Worked example: a small report

Here is a pipeline that uses several families at once. Imagine order lines as tuples of customer, item and amount:

FSHARP
let orders =
    [ ("Ada", "book", 12.5)
      ("Alan", "pen", 2.0)
      ("Ada", "pen", 2.0)
      ("Grace", "book", 12.5)
      ("Alan", "book", 12.5) ]

let report =
    orders
    |> List.groupBy (fun (customer, _, _) -> customer)
    |> List.map (fun (customer, lines) ->
        let total = lines |> List.sumBy (fun (_, _, amount) -> amount)
        customer, List.length lines, total)
    |> List.sortByDescending (fun (_, _, total) -> total)

for (customer, count, total) in report do
    printfn "%-6s %d orders %6.2f" customer count total

Output:

TEXT
Ada    2 orders  14.50
Alan   2 orders  14.50
Grace  1 orders  12.50

(The two customers with equal totals keep their original grouping order because the sort is stable.) Read the steps aloud: group by customer; for each group, sum and count; sort by total, highest first; print. No mutable counters, no index arithmetic.

Mini-practice

  1. Build the list of squares of the odd numbers from 1 to 15 with a comprehension.
  2. Use List.choose to extract the ints from ["10"; "abc"; "30"].
  3. Use List.windowed 2 to compute differences between consecutive items of [1; 4; 9; 16] (answer: [3; 5; 7]).
  4. Turn ["apple"; "avocado"; "banana"] into a map from first letter to the list of words, using List.groupBy and Map.ofList.

C# stand-ins

LINQ's SelectMany is the nested-for comprehension, and a query with from clauses reads similar to the F# version. These stand-ins reproduce the pairs, triples and the report.

C# C# stand-in: pairs and triples

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: the order report

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 does [ for i in 1 .. 4 -> i * 2 ] produce?

    Square brackets build a list, and the arrow yields i * 2 for each i.
  2. 2. How do you skip an element in a comprehension?

    If the branch does not yield, nothing is added for that iteration.
  3. 3. Which function maps and filters in one step when the mapping may fail?

    choose keeps the values inside Some and drops None.
  4. 4. What does seq { for i in 1 .. 5 -> i * i } differ in from the list version?

    A seq expression yields items lazily; the list version is computed immediately.

Summary

  • Comprehensions build lists ([ ... ]), arrays ([| ... |]) and sequences (seq { ... }) with for, if, yield and yield!.
  • Nested for clauses create combinations; guards filter.
  • Use comprehensions for multi-step generation and pipelines for transforming existing data.
  • Pick functions by intent: map, filter, choose, fold, groupBy, partition, tryFind, zip, windowed.

Chapter 5 turns to modeling data: records, unions and your own types.

Next: Records and Anonymous Records