Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 40 ยท Variants and Pattern Matching

Pattern Matching in Depth: match, Guards, Or-Patterns and More

Master OCaml pattern matching. Destructure tuples, lists, records and variants, use guards, or-patterns, as-bindings and exhaustiveness checks, and avoid common traps.

Pattern matching is how OCaml takes values apart. A match expression compares a value against a list of patterns from top to bottom and runs the code of the first one that fits, binding names to pieces of the value along the way. It replaces chains of if, getters and type checks with something shorter that the compiler can verify.

You saw simple matches in variant types. This lesson covers the whole pattern language.

OCaml is not available in the site's code runners, so the ocaml blocks are read-only. The Python stand-ins at the end use Python's own match statement (3.10+), which borrows the same idea.

The shape of a match

OCAML
let describe n =
  match n with
  | 0 -> "zero"
  | 1 | 2 | 3 -> "small"
  | n when n < 0 -> "negative"
  | _ -> "large"

Each arm is | pattern -> expression. All arms must return the same type. The wildcard _ matches anything and binds nothing.

What a pattern can be

Pattern Matches
42, 'a', "hi", true that exact constant
x anything, binding it to x
_ anything, no binding
(a, b) a tuple, binding both parts
h :: t a non-empty list: head and tail
[], [x], [x; y] an empty list, or a list of exactly that length
{ name; age } a record, binding fields by name
Some x, Node (l, v, r) a constructor and its arguments
p1 | p2 either pattern (or-pattern)
p as x pattern p, also binding the whole value to x
'a'..'z' a character range

Patterns nest freely. This function handles pairs of options:

OCAML
let add_opt a b =
  match a, b with
  | Some x, Some y -> Some (x + y)
  | Some x, None | None, Some x -> Some x
  | None, None -> None

The or-pattern Some x, None | None, Some x is legal because both sides bind the same variable x with the same type.

Matching lists

Lists are variants ([] and ::), so recursion over them is a match:

OCAML
let rec sum = function
  | [] -> 0
  | x :: rest -> x + sum rest

let rec pairs = function
  | a :: b :: rest -> (a, b) :: pairs rest
  | _ -> []

function is shorthand for fun x -> match x with, handy for single-argument functions.

Guards with when

A when clause adds a boolean condition to an arm:

OCAML
let classify = function
  | x when x mod 15 = 0 -> "FizzBuzz"
  | x when x mod 3 = 0 -> "Fizz"
  | x when x mod 5 = 0 -> "Buzz"
  | x -> string_of_int x

Use guards sparingly. The compiler cannot reason about them, so it assumes a guarded arm might not match, and it will ask for a final catch-all arm.

as-patterns and nested names

as keeps a whole value while you also inspect its parts:

OCAML
let rec dedupe = function
  | (x :: y :: _) as l when x = y -> dedupe (List.tl l)
  | x :: rest -> x :: dedupe rest
  | [] -> []

Exhaustiveness: the safety net

The compiler checks that your arms cover every possible value. If you forget one, you get a warning (compiled as an error in dune's default development profile):

OCAML
type light = Red | Amber | Green

let next = function
  | Red -> Green
  | Green -> Amber
(* Warning 8: this pattern-matching is not exhaustive.
   Here is an example of a case that is not matched: Amber *)

This is the superpower of variants. Add a constructor to a type and the compiler points at every match in the program that now needs updating.

A catch-all _ arm silences that check. If you write | _ -> ... for a variant you own, adding a new constructor later will silently fall into it. Prefer listing the cases explicitly for your own types and keep _ for open-ended types such as integers and strings.

The compiler also warns about unused arms, such as a pattern fully covered by an earlier one.

Matching in other places

Patterns appear outside match:

OCAML
let (q, r) = (17 / 5, 17 mod 5)          (* let-binding *)
let swap (a, b) = (b, a)                  (* function parameter *)
let { name; age } = { name = "Ada"; age = 36 }  (* needs a record type with those fields *)

let () =
  List.iter (fun (k, v) -> Printf.printf "%s=%d\n" k v) [ ("a", 1); ("b", 2) ]
(* prints: a=1 then b=2 *)

try ... with also uses patterns, over exceptions (see exceptions), and match can handle exceptions inline with | exception Not_found -> ....

Matching efficiently

The compiler turns a match into a decision tree or a jump table, so large matches on constructors are fast, usually a single jump on the constructor tag. Order matters for correctness (first match wins) but rarely for speed.

Stand-in: Python structural matching

Python Stand-in: match statement with guards and or-patterns

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 input()), it gets the next line from this box.

Unlike OCaml, Python does not check that the cases are exhaustive, which is why it is worth knowing what the OCaml compiler does for you.

Common mistakes

  • Shadowing instead of comparing. In match x with | y -> ... the y is a new variable that matches anything; it does not compare against an outer y. Use a guard (| v when v = y) to compare.
  • Missing parentheses around nested matches. An inner match swallows the following arms. Wrap it in ( ... ) or begin ... end.
  • Wildcards hiding bugs, as described above.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does | x :: rest -> match?

    The cons pattern splits a non-empty list into its first element and the rest.
  2. 2. What is true of an or-pattern such as Some x, None | None, Some x?

    Whichever side matches, the body must find the same names available.
  3. 3. Why is a catch-all _ arm risky for a variant type you own?

    New constructors fall into the wildcard silently instead of producing a non-exhaustive warning.
  4. 4. What does function do?

    It builds a one-argument function whose body is a match over that argument.

Summary

  • match tests patterns top to bottom, and the first one that fits wins.
  • Patterns can be constants, variables, tuples, lists, records, constructors, ranges, or-patterns and as bindings.
  • when guards add conditions but weaken exhaustiveness checking.
  • The compiler warns about non-exhaustive and unused arms. Use it as a to-do list when types change.

Next: Option and Result Types