Pattern matching

Equations as patterns

Several equations for one function are a pattern match written vertically. Each line is tried in order, and the first fit wins:

greeting :: Bool -> String greeting True = "hello again" greeting False = "hello"

The compiler checks the list of equations for gaps. With -Wall enabled it warns that the pattern match is non-exhaustive, which is the warning you should never ignore.

List patterns

A list is either empty or an element consed onto a tail. Those two patterns describe every list that exists:

sumList :: [Int] -> Int sumList [] = 0 sumList (x:xs) = x + sumList xs

The parentheses are mandatory: x:xs is a pattern, while x xs would be two arguments. Longer prefixes work the same way, as in (a:b:rest).

As-patterns

Sometimes you need both the parts and the whole. The at sign names the whole value while the pattern still destructures it:

describe :: [Int] -> String describe all@(x:_) | length all > 3 = "long list starting with " ++ show x | otherwise = "short list" describe [] = "empty"

Without all@ the function would have to rebuild the list from x and xs, which is wasteful and easy to get wrong.

Exhaustive or not

A match is exhaustive when every possible value fits some equation. GHCi lets you prove a failure in one line:

headOf :: [Int] -> Int headOf (x:_) = x -- headOf [] raises an exception at runtime

The standard head is partial in exactly this way, which is why production code prefers a case returning Maybe. Lesson 22 turns that preference into a rule.

The code on this page was run with GHC 9.10.3 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev