TExcelTAD
Home › OCaml › OCaml Pattern Matching

OCaml Pattern Matching

Pattern matching compares a value against a list of shapes, called patterns, and runs the branch of the first one that fits. It is one of OCaml's best features: it combines testing and taking apart data in one step, and the compiler checks that you covered every case.

ocaml · try it yourself
let day_name n =
  match n with
  | 1 -> "Monday"
  | 2 -> "Tuesday"
  | 3 -> "Wednesday"
  | 6 | 7 -> "weekend"
  | _ -> "another day"

let () = List.iter (fun d -> print_endline (day_name d)) [ 1; 3; 7; 5 ]
Monday
Wednesday
weekend
another day

The syntax is match expr with | pattern1 -> result1 | pattern2 -> result2 .... Like if, match is an expression, and every branch must have the same type. 6 | 7 is an or-pattern, and _ matches anything.

Kinds of patterns

Pattern Matches
42, 'a', "yes", true that constant
x anything, and binds it to x
_ anything, binds nothing
[] the empty list
x :: rest a non-empty list (head and tail)
[a; b] a list of exactly two elements
(a, b) a pair
Some x, None variant constructors
{ name; age } a record
p1 | p2 either pattern
'a' .. 'z' a character range
p as name p, and binds the whole value to name

Destructuring lists

ocaml · try it yourself
let rec pairs lst =
  match lst with
  | a :: b :: rest -> (a + b) :: pairs rest
  | [ last ] -> [ last ]
  | [] -> []

let () =
  pairs [ 1; 2; 3; 4; 5 ] |> List.iter (Printf.printf "%d ");
  print_newline ()
3 7 5 

Patterns can be nested to any depth: a :: b :: rest takes the first two elements at once.

Guards with when

A guard adds a boolean condition to a pattern:

ocaml · try it yourself
let classify temp =
  match temp with
  | t when t < 0 -> "freezing"
  | t when t < 15 -> "cold"
  | t when t < 25 -> "mild"
  | _ -> "hot"

let () = List.iter (fun t -> Printf.printf "%3d: %s\n" t (classify t)) [ -4; 9; 21; 33 ]
 -4: freezing
  9: cold
 21: mild
 33: hot

Matching on tuples

Matching on a tuple lets you decide on several values at once:

ocaml · try it yourself
let fizzbuzz n =
  match (n mod 3, n mod 5) with
  | 0, 0 -> "FizzBuzz"
  | 0, _ -> "Fizz"
  | _, 0 -> "Buzz"
  | _ -> string_of_int n

let () =
  List.init 15 (fun i -> fizzbuzz (i + 1)) |> String.concat " " |> print_endline
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

Exhaustiveness checking

If a match can fail, the compiler warns you and even shows an example of a value you forgot. The playground does not display warnings, but in your own project with dune they are errors by default in development builds:

ocaml
let first lst = match lst with
  | x :: _ -> x

Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
[]

At run time, a value that matches no branch raises the exception Match_failure, which stops the program unless it is caught (try ... with is covered in the exceptions lesson):

ocaml · try it yourself
let first lst = match lst with x :: _ -> x

let () =
  Printf.printf "%d\n" (first [ 5; 6 ]);
  match first [] with
  | n -> Printf.printf "%d\n" n
  | exception Match_failure _ -> print_endline "no branch matched []"
5
no branch matched []

Tip: Avoid a catch-all _ when matching on your own variant types. If you later add a new constructor, the compiler then points you at every match that needs updating.

function and as

function is shorthand for fun x -> match x with. as names a matched sub-value:

ocaml · try it yourself
let rec dedup = function
  | a :: (b :: _ as rest) when a = b -> dedup rest
  | a :: rest -> a :: dedup rest
  | [] -> []

let () =
  dedup [ 1; 1; 2; 3; 3; 3; 1 ] |> List.iter (Printf.printf "%d ");
  print_newline ()
1 2 3 1 

Test yourself

Which pattern matches a list with at least two elements?

  1. [a; b]
  2. a :: b :: rest
  3. a :: rest
  4. (a, b)

What does the compiler do when a match does not cover all cases?

  1. Nothing
  2. It issues a warning showing an unmatched example
  3. It adds a default branch silently
  4. It refuses to run the program on all platforms

What is when used for in a match?

  1. Looping
  2. Adding a boolean guard to a pattern
  3. Catching exceptions
  4. Binding a name