Pattern Matching

Pattern matching is a way of inspecting a value by comparing it against one or more patterns. Each pattern describes a shape the value might have; when a pattern matches, the variables inside it are bound to the corresponding pieces of the value. The Haskell 2010 Report describes the mechanism precisely: pattern matching proceeds “from left to right, and outside to inside,” and a match either fails, succeeds while binding variables, or diverges. Patterns can appear in lambda abstractions, function definitions, pattern bindings, list comprehensions, do expressions, and case expressions.

The central construct is the case expression. The Haskell Report notes that the other places patterns appear ultimately translate into case expressions, so the semantics of case underpin the whole feature. A case expression lists several alternatives, each a pattern paired with a result, and selects the first alternative whose pattern matches the scrutinized value.

Pattern matching is the natural way to take apart algebraic data types: each constructor of a sum type becomes one branch, and the data carried by that constructor is bound to fresh variables in the branch. Because the compiler knows all the constructors, it can warn when a set of branches is not exhaustive, catching cases a programmer forgot to handle.

The same idea appears across the ML family and beyond. The OCaml manual documents patterns built from constructors, tuples, records, variables, and wildcards, with the underscore wildcard matching anything without binding a name. This shape-directed style replaces nested conditionals and explicit field access with a single, readable description of every case a value can take.