Skip to content
match Expressions
step 1/5

Reading — step 1 of 5

Learn

~1 min readPattern Matching

match is OCaml's switch — but it matches by structure, binds variables, and is checked for exhaustiveness:

let describe n =
  match n with
  | 0 -> "zero"
  | n when n > 0 -> "positive"
  | _ -> "negative"

Patterns:

  • 0 — literal
  • n — bind to name (catches everything from there on)
  • n when ... — guard
  • _ — wildcard
  • (a, b) — tuple
  • [], [x], [x; y], x :: xs — list patterns
  • Some x, None — option

Lists are central to OCaml. The :: (cons) pattern destructures into head and tail:

let rec sum lst =
  match lst with
  | [] -> 0
  | x :: xs -> x + sum xs

The compiler warns when you miss a case. Pattern matches that don't cover all possibilities are flagged at compile time — a major safety feature.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…