jonnifyfsharp

Module C1.05

Pattern matching & active patterns

Branch on the shape of data, not on a single value — and name your own cases.

F#'s match is not a switch on a number. A pattern is a shape: it tests the structure of a value and binds the pieces in the same step. A list arm x :: rest matches a non-empty list and names its head and tail at once; a tuple arm (a, b) pulls a pair apart. Arms run top to bottom, first match wins, and the compiler checks that the cases are exhaustive. This module climbs in three dives — the core match expression and its pattern kinds, the refinements (when guards, or-patterns, destructuring in let), and active patterns: F#'s way of letting a programmer add named cases to the matcher.

Branching by structure, in three dives

Earlier modules built and wired functions; this one selects which one to run. The selection turns on shape. The three dives below move from the plain match to a matcher you extend yourself. Select one to read its summary and the one idea it adds.

The first dive names the pattern kinds — constant, wildcard, variable, tuple, list/cons, and as — and the rule that the first matching arm wins. The second adds the when guard (a boolean test on an arm), or-patterns, and destructuring outside match. The third covers active patterns: a complete one such as (|Even|Odd|) partitions every input, and a partial one such as (|Int|_|) returns an option and may decline to match.

The three dives · select one

C1.05.1 match expressions C1.05.2 guards & destructuring C1.05.3 active patterns the matcher your own cases
C1.05.1 · Match expressions

The core match expression and its pattern kinds: constant, wildcard, variable, tuple, list/cons, and as. Arms run top to bottom; the first match wins.

You learn how a pattern decomposes a value and binds its parts

Open this dive · or pick another above

A pattern is a shape. Match the shape, bind the pieces, run the arm — and, with active patterns, teach the matcher new shapes of your own.

The three dives

Read them in order. Each stands on valid, runnable F#: every match, every guard, and every active pattern below can be typed into dotnet fsi and produces exactly what the page shows.

live module hub built dive ready soon specified

References

Sources

Related in this course