Skip to content
match Expressions
step 1/5

Reading — step 1 of 5

Learn

~1 min readPattern Matching and Types

match is the heart of F#. It's a switch that destructures by shape:

let describe n =
    match n with
    | 0 -> "zero"
    | n when n > 0 -> sprintf "positive: %d" n
    | n -> sprintf "negative: %d" n      // catches everything else

Patterns:

  • 0 — literal
  • n — bind to name
  • n when ... — guard
  • _ — wildcard (matches anything, doesn't bind)
  • (a, b) — tuple
  • [x; y; z] — list of exact length 3
  • head :: tail — non-empty list (head is first, tail is the rest)
  • [] — empty list
  • Some x / None — option destructuring

Matches must be exhaustive. The compiler warns if you miss a case. This is huge for safety — when you add a new variant, the compiler tells you exactly which match expressions need updating.

Discussion

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

Sign in to post a comment or reply.

Loading…