F# · Lesson 3
Collections
Lists, arrays and lazy sequences, the List module (map, filter, fold, groupBy...) and data pipelines.
In short
- Lists by default:
[ 1; 2; 3 ],::to prepend,@to join - Arrays for .NET APIs and fast indexing;
seqfor lazy data - Chain
Listfunctions with|>: the collection almost always comes last List.foldis reduce; comprehensions build liststryfunctions return options instead of throwing
Most day-to-day F# code is "take some data, transform it, summarise it". That's done with three
collection types and a big library of functions that you chain with |>.
Lists
let prices = [ 4.5; 12.0; 7.25 ] // float list
let empty : int list = []
let more = 1.0 :: prices // prepend: [1.0; 4.5; 12.0; 7.25]
let all = prices @ [ 3.0; 9.0 ] // concatenate two lists
let first = List.head prices // 4.5 (throws on an empty list!)
const prices: number[] = [4.5, 12, 7.25];
const more = [1, ...prices];
const all = [...prices, 3, 9];
Line by line:
- Elements are separated by semicolons, not commas. On separate lines you can drop the
;:▶ Trylet cities = [ "Lisbon" "Oslo" "Kyoto" ] - The type is written
float list(orlist<float>). ::("cons") puts one element in front of a list. It's O(1).@joins two lists. It copies the left list, so avoid it in tight loops.- F# lists are immutable singly-linked lists. "Adding" creates a new list that shares the old one's elements. Nothing is ever modified in place.
Ranges and comprehensions
let oneToFive = [ 1 .. 5 ] // [1; 2; 3; 4; 5]
let tens = [ 0 .. 10 .. 50 ] // [0; 10; 20; 30; 40; 50]
let countdown = [ 5 .. -1 .. 1 ] // [5; 4; 3; 2; 1]
let squares = [ for n in 1 .. 5 -> n * n ] // [1; 4; 9; 16; 25]
let evens =
[ for n in 1 .. 10 do
if n % 2 = 0 then yield n ] // [2; 4; 6; 8; 10]
[ for x in xs -> expr ] is a map; add do + if to filter. yield can usually be omitted.
[ 1 .. 0 ] is simply [].
Arrays
let scores = [| 90; 75; 88 |] // int array (also written int[])
let firstScore = scores[0] // O(1) indexing
scores[1] <- 80 // elements are mutable!
let len = scores.Length
Arrays are fixed-size, mutable, and fast to index: the same thing as a .NET array. You'll meet
them constantly because .NET APIs return them ("a,b".Split(',') is a string[]). Convert with
List.ofArray / Array.ofList.
Sequences (lazy)
let naturals = Seq.initInfinite id // 0, 1, 2, ... never ends
let firstEvens = naturals |> Seq.filter (fun n -> n % 2 = 0) |> Seq.take 3 |> List.ofSeq // [0; 2; 4]
let lines = seq { for i in 1 .. 1000000 -> $"line {i}" } // nothing computed yet
seq<'T> is .NET's IEnumerable<T>, the equivalent of a JS iterator or generator: items are
produced on demand. Lists and arrays are also sequences, so any Seq function accepts them.
Use seq for large or infinite data and streaming; use lists by default.
The List module
Almost every operation is a function in the List module (with twins in Array and Seq).
The collection is almost always the last argument (List.foldBack is the exception), so they chain with |>.
| F# | What it does | TypeScript |
|---|---|---|
List.map f | transform each item | .map(f) |
List.filter p | keep matching items | .filter(p) |
List.sum, List.sumBy f | add up | .reduce((a, x) => a + f(x), 0) |
List.averageBy f | mean (throws on empty) | |
List.fold f init | accumulate a state | .reduce(f, init) |
List.reduce f | fold without init (throws on empty) | .reduce(f) |
List.sortBy f, List.sortByDescending f | sorted copy | [...xs].sort(...) |
List.groupBy f | (key, items) list | Object.groupBy |
List.countBy f | (key, count) list | |
List.distinct | remove duplicates | [...new Set(xs)] |
List.choose f | map to option, keep the Somes | .flatMap(x => cond ? [y] : []) |
List.collect f | map to lists, then flatten | .flatMap(f) |
List.tryFind p | first match as an option | .find(p) |
List.exists p, List.forall p | any / all | .some(p), .every(p) |
List.zip a b | pair up two lists | |
List.truncate n, List.skip n | first n / drop n | .slice(0, n), .slice(n) |
List.length, List.isEmpty, List.rev | .length, .length === 0, .reverse() | |
List.maxBy f, List.minBy f | biggest / smallest item by key |
List.fold deserves a closer look, because it's the general tool behind most of the others:
let total = [ 3; 5; 2 ] |> List.fold (fun acc x -> acc + x) 0 // 10
const total = [3, 5, 2].reduce((acc, x) => acc + x, 0);
Options in 60 seconds
List.tryFind, List.tryHead and List.choose use the option type: a value that may be missing.
let found = [ 3; 8; 12 ] |> List.tryFind (fun n -> n > 5) // Some 8
let missing = [ 3 ] |> List.tryFind (fun n -> n > 5) // None
let describe (result: int option) : string =
match result with
| Some n -> $"found {n}"
| None -> "nothing"
let orZero = missing |> Option.defaultValue 0 // 0
Think number | undefined, except the compiler forces you to handle None before you can use the
number. match is covered in depth later. For now, read it as a switch over the two cases.
Tuples, briefly
Grouping and counting functions return tuples: ("ERROR", 3) has type string * int
(TypeScript [string, number]). Take them apart with fst/snd or in a lambda:
fun (level, count) -> .... The next topic covers them properly.
Pipelines over data
Here's a realistic pipeline: top customers by spend, ignoring small orders.
let orders = [ ("alice", 120.0); ("bob", 35.5); ("alice", 18.0); ("carol", 99.9); ("bob", 80.0) ]
let topCustomers =
orders
|> List.filter (fun (_, amount) -> amount >= 20.0)
|> List.groupBy fst
|> List.map (fun (customer, items) -> customer, items |> List.sumBy snd)
|> List.sortByDescending snd
// [("alice", 120.0); ("bob", 115.5); ("carol", 99.9)]
const totals = new Map<string, number>();
for (const [customer, amount] of orders.filter(([, a]) => a >= 20)) {
totals.set(customer, (totals.get(customer) ?? 0) + amount);
}
const topCustomers = [...totals].sort((a, b) => b[1] - a[1]);
Each step is a pure function of the previous result, so you can comment out the tail and look at any intermediate value. That's how F# developers debug pipelines.
Common beginner mistakes
- Commas in list literals.
[1, 2, 3]is a list containing one tuple(1, 2, 3). Use[1; 2; 3]. ::with the list on the left.xs :: 4doesn't compile;::adds one item at the front. To append, usexs @ [ 4 ](or build the list backwards andList.revit once).- Functions that throw on empty lists:
List.head,List.reduce,List.average,List.max,List.maxBy. Check for empty first (List.isEmpty), or use thetryversions where they exist (List.tryHead,List.tryFind,List.tryItem...). There is noList.tryMax; guard withif List.isEmpty xs then ... else List.max xs. - Argument order. It's
List.map f xs, notList.map xs f. With a pipe:xs |> List.map f. - Lambda can't see the type.
List.map (fun s -> s.Length) wordsmay fail with "Lookup on object of indeterminate type". Writewords |> List.map (fun s -> s.Length): the pipe lets inference seewordsfirst. List.averageon ints. It only works on floats/decimals. UseList.averageBy float.- Indexing lists in a loop.
xs[i]on a list is O(i). Use List functions or an array. - Forgetting laziness. A
seqre-runs its work (and side effects) every time it's enumerated. Materialise it withList.ofSeqif you need it twice. List.skip/List.takethrow if there aren't enough items.List.truncateis the safe "at most n".
Cheat sheet
[ 1; 2; 3 ] [| 1; 2; 3 |] seq { 1 .. 3 } // list, array, lazy seq
x :: xs xs @ ys [ 1 .. 10 ] // cons, append, range
[ for x in xs do if x > 0 then x * 2 ] // comprehension
xs |> List.map f |> List.filter p |> List.sum // pipeline
xs |> List.fold (fun acc x -> acc + x) 0 // reduce with initial state
xs |> List.groupBy key |> List.map (fun (k, items) -> k, List.length items)
xs |> List.countBy key // (key * int) list
xs |> List.sortByDescending snd |> List.truncate 3
xs |> List.tryFind p |> Option.defaultValue fallback
xs |> List.choose tryParse // keep only successful parses
List.ofArray arr Array.ofList xs List.ofSeq s // conversions
Practise this lesson
In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.
Open in the app