Pattern Matching
Sum and product types built trees out of constructors, but so far a program can only
compare them with ==. It has no way to get the 7 back out of a Num(7). The program below adds
two functions over the Arith type declared there. value computes the number a tree stands for.
simplify walks down the tree removing additions of zero and multiplications by one, using the
identities , , , and :
type Arith = Num(Int) | Add(Arith, Arith) | Mul(Arith, Arith);
fn simplify(e: Arith) -> Arith = match e {
Add(Num(0), r) => simplify(r),
Add(l, Num(0)) => simplify(l),
Mul(Num(1), r) => simplify(r),
Mul(l, Num(1)) => simplify(l),
Add(l, r) => Add(simplify(l), simplify(r)),
Mul(l, r) => Mul(simplify(l), simplify(r)),
Num(n) => Num(n),
};
fn value(e: Arith) -> Int = match e {
Num(n) => n,
Add(l, r) => value(l) + value(r),
Mul(l, r) => value(l) * value(r),
};
fn main() {
let e = Add(Num(0), Mul(Num(1), Add(Num(7), Num(0))));
println(simplify(e));
println(value(e));
println(simplify(Add(Num(0), Num(0))));
}
It prints:
Num(7)
7
Num(0)
Each arm of a match pairs a pattern with an expression. The value being examined, e here, is
the scrutinee. Reading the arms raises these questions:
- How does one pattern both test and name?
Add(Num(0), r)checks two constructors and a literal, and it also gives a name to part of the value. - Which arm runs when several fit?
Add(Num(0), Num(0))fits the first two arms and the fifth. - What is
r, to the checker? No annotation gives it a type, yetsimplify(r)has to check. - What happens if no arm fits? Nothing in the syntax requires the arms to cover every tree.
From cases to equations
Rod Burstall’s “Proving Properties of Programs by Structural
Induction” (1969) needed programs whose definitions
followed the structure of their data, so that a proof could follow it as well. He proposed a cases
expression over constructors, with which list concatenation looks like this:
let rec concat(xs1, xs2) = cases xs1:
cons(x, xs3): cons(x, concat(xs3, xs2))
nil( ) : xs2
He gave a source for the idea: “These cases expressions were partly suggested by a case switch on
type introduced into CPL by M. Richards (1967).” David Turner’s SASL moved the patterns to the
definition itself. By Turner’s
account, its 1976 revision began
“allowing multi-equation function definitions, thus extending the use of pattern matching to case
analysis”, so that length was written as one equation per list shape. In
Hope, the left-hand side of each equation
“includes a pattern used to determine which equation to use for a given argument”. Bridger’s match
is an expression in the style of Burstall’s cases, and its patterns nest as Hope’s do.
The shape of a value, with holes
A pattern is written like the expression that would build the value it describes, with names or wildcards in the places the pattern does not constrain. Appendix B gives the grammar:
pattern ::= '_' | literal | ident
| UpperIdent [ '(' pattern { ',' pattern } ')' ]
| '(' pattern ')'
| '(' pattern ',' pattern { ',' pattern } ')'
| '[' [ pattern { ',' pattern } [ ',' '...' ident ] ] ']'
| pattern '::' pattern
| UpperIdent '{' [ field_pat { ',' field_pat } [ ',' ] ] '}'
| pattern '|' pattern ;
field_pat ::= ident [ ':' pattern ] ;
| Pattern | Matches | Binds |
|---|---|---|
_ | any value | nothing |
x | any value | x to the value |
0, "sat", true, () | a value equal to the literal | nothing |
Some(p) | a Some whose argument matches p | what p binds |
(p, q) | a tuple whose components match | what p and q bind |
[p, q] | a list of exactly two matching elements | what p and q bind |
[p, ...t] | a list of at least one element, its first matching p | what p binds, and t to the rest |
h :: t | a non-empty list whose head and tail match | what h and t bind |
Point { x: p } | a Point whose field x matches p; other fields may be anything | what p binds |
p | q | a value matching p or q | the variables both sides bind |
Patterns nest to any depth, because each position holding a pattern accepts every form in the table.
Add(Num(0), r) is a constructor pattern whose first argument is another constructor pattern whose
own argument is a literal. These functions use several of the forms:
fn describe(xs: [Int]) -> String = match xs {
[] => "empty",
[x] => "one: " ++ to_string(x),
[x, y] => "two",
[x, ...rest] => "starts with " ++ to_string(x),
};
fn sign(n: Int) -> String = match n {
0 => "zero",
x if x < 0 => "negative",
_ => "positive",
};
fn weekend(d: String) -> Bool = match d {
"sat" | "sun" => true,
_ => false,
};
An arm can also carry an if condition, called a guard, as sign does with x if x < 0.
Guards are covered below.
The matching relation
Whether a pattern fits a value, and what it binds if so, is the partial function . It returns a binding , a finite map from the pattern’s variables to values, or when the value does not fit:
The disjoint union combines the bindings of the subpatterns, and it is if any
subpattern gives . Any pair the equations do not list, such as a constructor pattern against a
different constructor, also gives . A list pattern behaves as the conses
it abbreviates, ending in the empty list, and with ...t it ends in the variable t. The full
relation, with struct patterns, is in Appendix
D.
Here is the first arm of simplify against a value it fits:
Against Add(Num(3), Num(5)), the same calculation reaches ,
and the whole result is .
match evaluates its scrutinee once. It then takes the first arm whose pattern matches and
whose guard, if it has one, evaluates to true:
An arm with no guard is the case . The premise about fixes the order:
arms are tried from top to bottom. Add(Num(0), Num(0)) fits three arms of simplify, and the
first one runs. If no arm qualifies, no rule applies and evaluation is stuck, which the evaluator
reports as NonExhaustiveMatch.
The variables of are in scope in the guard and the body of arm only. Like a let,
they shadow an outer binding of the same name:
let x = 1;
let v = match Some(5) { Some(x) => x + 1, None => x };
println(v); // 6
println(x); // 1
Typing patterns
A pattern is checked against the type of the scrutinee, and the judgment produces the types of its variables:
It reads pattern matches a value of type and binds the variables in . A wildcard binds nothing, and a variable takes the whole type:
A constructor pattern looks up its argument types in the declaration, instantiated with the scrutinee’s type arguments, and combines the bindings of its subpatterns:
Tuple, list, cons, and struct patterns work the same way, and a literal pattern requires the
scrutinee to have the literal’s type and binds nothing. In Add(Num(0), r) against Arith, the
declaration says that Add’s second argument is an Arith, so with
no annotation. Against Option<Int>, Some(x) gives .
The rule for match extends the context with each arm’s bindings and requires every arm’s body to
have one type:
The last premise is the subject of Exhaustiveness checking. A pattern that cannot fit the scrutinee’s type is an error at the pattern:
// with o : Option<Int>
match o { "s" => 1, _ => 0 }
// type mismatch: expected Option<Int>, found String
match o { Some(a, b) => 1, _ => 0 }
// `Some` takes 1 argument(s), given 2
Bridger’s match
Names in patterns
An identifier in a pattern always binds. This program prints at the limit, because the arm
limit makes a new variable that matches any value:
fn main() {
let limit = 10;
let n = 3;
println(match n {
limit => "at the limit",
_ => "somewhere else",
});
}
A comparison with an existing variable goes in a guard: x if x == limit => …. Constructors are
UpperCamelCase and variables are lowercase, so the case of the first letter tells the parser which
one a name is, and None in a pattern is the constructor.
Guards
A guard is an extra condition on an arm, evaluated after the pattern matches, with the pattern’s
variables in scope. If it is false, matching moves on to the next arm. E-Match’s premise requires
the guard to leave the store and database as it found them, and the checker enforces that with the
purity judgment that rule filters use:
match Some(1) { Some(x) if { println("g"); true } => x, _ => 0 }
// this match guard is not pure
The judgment has to treat an unknown function as possibly impure, so a guard cannot call a function
parameter. filter written with a guard, x :: rest if keep(x) => …, is rejected, and the test
goes in the arm’s body instead, as below.
Alternatives
An or-pattern p | q lets one arm cover several shapes. Because the same body runs whichever side
matched, both sides must bind the same variables at the same types. L(x) | N => 1 is rejected
because x would be undefined when the value was N.
One binding per name
A pattern may bind each name once. The pattern (x, x) reads as if it tests two components for
equality, but Bridger rejects it with NonLinearPattern, and the equality goes in a guard: (x, y) if x == y. This property is called linearity, and it is what makes the unions in
disjoint. It also keeps in the constructor pattern’s
typing rule from giving one variable two types.
Taking lists apart
The list patterns are what Recursion and higher-order functions was waiting for. The prelude’s list functions can now be written in Bridger:
fn my_map<A, B>(xs: [A], f: fn(A) -> B) -> [B] = match xs {
[] => [],
x :: rest => f(x) :: my_map(rest, f),
};
fn my_filter<A>(xs: [A], keep: fn(A) -> Bool) -> [A] = match xs {
[] => [],
x :: rest =>
if keep(x) { x :: my_filter(rest, keep) } else { my_filter(rest, keep) },
};
fn my_fold<A, B>(xs: [A], acc: B, f: fn(B, A) -> B) -> B = match xs {
[] => acc,
x :: rest => my_fold(rest, f(acc, x), f),
};
fn main() {
println(my_map([1, 2, 3], |x: Int| x * 10));
println(my_filter([1, 2, 3, 4], |x: Int| even(x)));
println(my_fold([1, 2, 3], 0, |a: Int, x: Int| a + x));
}
It prints:
[10, 20, 30]
[2, 4]
6
Each function has one arm per way of building a list, and its recursion follows the recursion in the
list type. The same pattern opens the Option that Querying
relations left closed: match head(solutions before(?c, ?c)) { Some(c) => c, None => "none" }.
Propagating failure with ?
Error handling introduced ? as sugar over match and return. With
match available, the definition is short. On a Result, e? means
match e { Ok(v) => v, Err(err) => return Err(err) }
and on an Option it means
match e { Some(v) => v, None => return None }
head and tail each return an Option, and this function needs both of them to succeed:
fn sum_first_two(xs: [Int]) -> Option<Int> {
let a = head(xs)?;
let rest = tail(xs)?;
let b = head(rest)?;
Some(a + b)
}
fn main() {
println(sum_first_two([1, 2, 3]));
println(sum_first_two([1]));
}
It prints:
Some(3)
None
The enclosing function’s result type has to be able to carry the failure. A ? on an Option
inside a function returning Int or a Result is a type error. Until traits
supply a conversion, a ? on a Result also requires the function’s error type to be the same E.
Building it
An arm and a pattern reach the evaluator as the AST chapter defined them:
struct Arm {
pat: Pattern, // the pattern this arm matches
guard: Option<Expr>, // an optional `if` guard
body: Expr, // evaluated when the arm is taken
}
enum Pattern {
Wild(Span), // _
Lit(Lit, Span), // a literal: 5, true, "hi"
Var(Name, Span), // binds the matched value to a name
Ctor(Name, Vec<Pattern>, Span), // a constructor: C(p, …)
Tuple(Vec<Pattern>, Span), // (p, p, …), two or more
List(Vec<Pattern>, Option<Name>, Span), // [p, …], with an optional ...rest
Cons(Box<Pattern>, Box<Pattern>, Span), // head :: tail
Struct(Name, Vec<(Name, Pattern)>, Span), // S { f: p, … }
Or(Box<Pattern>, Box<Pattern>, Span), // p | p
}
The matcher is one recursive function with an arm per Pattern variant, following
: given a pattern and a value, it either produces the bindings or reports that the
value does not fit. A failed match is an ordinary outcome that moves on to the next arm, and it does
not become a RuntimeError.
The evaluator’s Match arm evaluates the scrutinee once and walks the arms in order. For each arm
whose pattern fits, it extends the environment with the bindings, evaluates the guard if there is
one, and evaluates the body if the guard held. Reaching the end of the arms is a stuck
NonExhaustiveMatch blamed on the match. The Try arm is the desugaring above, with the failing
case using the same signal that return does.
The checker’s check_pattern follows the judgment , extending a copy of
the context per arm, and it is where NonLinearPattern and OrPatternBindings are raised. The
Match arm checks the scrutinee, checks each arm’s pattern, guard, and body against a common result
type, and finally runs the exhaustiveness check described in the next chapter.
The design space
Matching and unification
Unification also compares two structures and produces bindings, but
variables may appear on both sides, and solving them can take several steps. Matching has variables
on one side only, the pattern, while the value is fully known, so one walk over the pattern decides
it. Prolog’s clause selection uses unification, which lets a call pass an unbound variable and
receive a structure back. A Bridger match runs in one direction, from the value to the bindings.
Repeated variables
Prolog, Erlang, and SASL read a repeated variable as an equality test, so a pattern like (x, x)
matches a pair of equal components. OCaml, Haskell, Rust, and Python reject it, as Bridger does.
Accepting it makes equality an implicit part of matching, which Bridger cannot offer at every type,
because == is not defined on functions.
What a name means
Python’s match statement uses the same rule as Bridger: a bare name in a case binds and matches
anything. Python has no capitalization convention to separate a constructor from a variable, and
case limit: silently captures in the way this chapter’s limit arm does. A dotted name such as
Config.limit is compared instead. OCaml, Haskell, and Rust use the capitalization of names, by
rule or by convention, as Bridger does.
Order and compilation
Arms tried from top to bottom make meaning depend on order, which lets a later arm act as a general
case behind earlier special ones, as Add(l, r) does in simplify. Bridger’s evaluator tries the
arms one at a time. Compilers for pattern-matching languages translate a match into a tree of tag
tests, with the same results as the top-to-bottom reading. Philip Wadler’s chapter in Simon Peyton
Jones’s The Implementation of Functional Programming
Languages
(1987) describes such a compiler and credits Lennart Augustsson’s LML compiler with its first
published description. The chapter before it gives the semantics being compiled: “The equations are
tried out one at a time, from top to bottom.”
Patterns and abstraction
A pattern names a type’s constructors, so a function that matches on a type depends on how it is
represented. Changing Arith’s constructors changes every match on it. Some languages let a
programmer define new patterns that run code to decide whether they match, separating the pattern a
client writes from the representation underneath. Wadler’s
“Views” (1987) lets any type be seen as
a sum of constructors chosen for the purpose, and F# provides active
patterns. Bridger’s patterns are structural only, so
matching runs no code other than the guards.
Statements and expressions
C’s switch is a statement over integers, whose cases fall through to the next unless a break
intervenes. Python’s match is also a statement. In Bridger, Rust, and the ML family, match is an
expression with a value, so all of its arms need one type.
Further reading
Programs that follow their data: Burstall’s
“Proving Properties of Programs by Structural Induction”
(1969) develops cases alongside proofs about lists and trees, and it is eight pages long.
Compiling matches: Chapters 4 and 5 of Peyton Jones’s The Implementation of Functional Programming Languages give the semantics of equations with patterns and an algorithm that turns them into case expressions, in that order.
A recent design: PEP 635 records the rationale for Python’s
match, including why bare names capture and which alternatives were rejected.
Patterns and abstraction: Syme, Neverov, and Margetson’s “Extensible Pattern Matching via a Lightweight Language Extension” (2007) describes F#’s active patterns and compares them with views.
Concept checks
What does simplify(Mul(Num(1), Num(1))) return, which arm fires at each step, and what if the arm order put Mul(l, r) first?
The third arm fires, binding r to Num(1), and simplify(Num(1)) takes the last arm and returns
Num(1). With Mul(l, r) first, that arm would match every multiplication and the identity arms
would never run, so the result would be Mul(Num(1), Num(1)).
simplify(Add(Mul(Num(1), Num(0)), Num(5))) returns Add(Num(0), Num(5)), which still adds zero. Why, and how could simplify be changed to remove it?
The patterns test the tree as it was on the way down. The Add has a Mul as its left operand, so
neither identity arm fits and the general Add(l, r) arm runs. Only then does the left operand
simplify to Num(0), and nothing matches the new Add that the arm builds. A bottom-up version
simplifies the operands first and matches on the results, with an arm such as Add(l, r) => match (simplify(l), simplify(r)) { (Num(0), b) => b, (a, Num(0)) => a, (a, b) => Add(a, b) }. It returns
Num(5) here, at the cost of the single flat list of arms.
What is match([x, ...t], [1, 2]), and what are match(x :: y :: t, [1]) and match([x], [1, 2])?
The first is . The second is : x takes 1, and then y :: t
meets the empty list, which is not a cons. The third is also , because [x] abbreviates x :: [] and the tail [2] is not empty.
In the arm Some(x) | None => 0, what goes wrong, and how does the same pattern fare if x is replaced by _?
The sides bind different variables, so x would have no value when the scrutinee was None, and
the checker rejects the pattern with OrPatternBindings. With _ neither side binds anything, and
the pattern is accepted. It then matches every Option.
Bridger rejects a guard that calls a function parameter. Name what the rule protects, and describe what a language gives up by allowing arbitrary guards.
The rule protects E-Match’s premise that a failed guard changes nothing, so trying arms has no
effect other than choosing one, and the evaluator or a compiler is free to run guards in any
consistent way. Arbitrary guards are more convenient, as my_filter’s guard would have been, but
then an arm can change the store and still fail, and the program’s behaviour depends on exactly how
many guards were run.