Pattern Matching
Pattern matching is how silt branches. No if, no ternary, no switch: a
choice is a match, and the compiler checks exhaustiveness. when ... else
(below) leaves a block early when a pattern or a condition fails.
Match with Scrutinee
fn describe(shape) {
match shape {
Circle(r) -> "circle with radius {r}"
Rect(w, h) -> "rect {w}x{h}"
}
}
Each arm starts on its own line; there is no separator between arms. A match
with one arm may be written on one line: match pair { (a, b) -> a + b }.
An arm’s body is one expression; statements take a block, p -> { ... },
whose last expression is the arm’s value. One expression needs no braces, and
silt fmt takes them away: 0 -> { "done" } becomes 0 -> "done". (It
leaves them where taking them away would move a comment to the next arm or
change how the next arm is read, and inside a string it keeps as written.)
The body may stand on the line after the ->, one level deeper. silt fmt
first lays out the arm’s pattern and guard: it breaks them over lines when
they do not fit their line together with the start of the body (up to the
first place the body can break, such as the ( of a call). Then it puts the
body on the next line when the body does not fit behind the -> but fits
that line.
Match without Scrutinee (Boolean Dispatch)
Omit the scrutinee for boolean conditions:
fn classify(n) {
match {
n == 0 -> "zero"
n > 0 -> "positive"
_ -> "negative"
}
}
The arms are tried in order and the first true condition wins. Such a match
must end with a _ -> ... arm, the value when no condition is true; leaving
it out is a type error. _ is the one arm that always matches: a condition
that is the literal true is _ written another way, and one that is the
literal false never holds, so its arm never runs; both are warnings
(W0304). An arm after one that always matches never runs, which is a
warning (W0303), as for a match on a value (below).
Literal Patterns
Including negative numbers:
match n {
0 -> "zero"
1 -> "one"
-1 -> "negative one"
_ -> "other"
}
Works for Int, Float, String, and Bool.
Constructor and Nested Patterns
fn handle(result) {
match result {
Ok(Some(value)) -> use(value)
Ok(None) -> handle_empty()
Err(e) -> handle_error(e)
}
}
Qualified Patterns
Constructors and record types from another module are named through
the module (or its alias): m.Variant, or m.Enum.Variant, which
always works, even when two enums of the module share a variant name.
Inside the declaring module, Enum.Variant works too:
-- noexec (multi-file: shapes.silt declares `pub type Shape { Circle(Float), Rect(Float, Float) }`)
import shapes
fn describe(s) {
match s {
shapes.Circle(r) -> "circle {r}"
shapes.Shape.Rect(w, h) -> "rect {w}x{h}"
}
}
Qualified patterns work in every pattern position — match arms,
when let, let, or-patterns, and nested sub-patterns — and the
qualifier picks the right type when two imported modules export the
same name (a.Pt { x, .. } vs b.Pt { label, .. }). Naming the wrong
module or enum is a type error.
Tuple Patterns
fn fizzbuzz(n) {
match (n % 3, n % 5) {
(0, 0) -> "FizzBuzz"
(0, _) -> "Fizz"
(_, 0) -> "Buzz"
_ -> "{n}"
}
}
Record Patterns
Use .. to ignore remaining fields:
fn greet(user) {
match user {
User { name, active: true, .. } -> "hello {name}"
User { name, .. } -> "{name} is inactive"
}
}
List Patterns
Three forms: empty [], exact length [a, b, c], and the first elements
with a rest after them, [h, ..t]. The rest is ..name, which binds the
list of the remaining elements, or a bare .. when they are not needed:
fn sum(xs) {
match xs {
[] -> 0
[head, ..tail] -> head + sum(tail)
}
}
fn first_of_two_or_more(xs) {
match xs {
[a, _, ..] -> Some(a)
_ -> None
}
}
Nested patterns work in list elements: [Some(a), Some(b), ..rest]. The
rest comes last and is a name or nothing. The bare .. matches the record
rest pattern (User { name, .. }).
Map Patterns
match config {
#{ "name": name, "greeting": greeting } -> "{greeting}, {name}!"
#{ "name": name } -> "hello, {name}!"
_ -> "hello, stranger!"
}
A map pattern is open: #{ "name": name } matches a map with more keys
too. So a map pattern names at least one key: #{} would test nothing
and match every map, not only the empty one, and it is an error (“a map
pattern without keys tests nothing”). _ takes every map, and a guard
tests for the empty one: m when map.is_empty(m) -> ....
A key written twice in one map pattern is an error (duplicate key "a" in map pattern): the pattern could never match, or would give one value
two names.
Or-Patterns
Match multiple alternatives in a single arm with |:
match n {
0 | 1 -> "small"
2 | 3 -> "medium"
_ -> "large"
}
A long list of alternatives may continue on the next line, which then
starts with its |:
match day {
"Saturday"
| "Sunday" -> "weekend"
_ -> "weekday"
}
All alternatives must bind the same variables (and, as in any match,
all alternatives must have the same type — you can’t mix Some(x) with
Ok(x) in one or-pattern):
-- OK: both alternatives bind `x`
fn unwrap_either(r: Result(Int, Int)) -> Int {
match r {
Ok(x) | Err(x) -> x
}
}
fn main() {
println("{unwrap_either(Ok(7))}") -- 7
}open in playground-- ERROR: first alternative binds x, second binds y
Ok(x) | Err(y) -> ...
-- compile error: or-pattern alternatives must bind the same variables
Naming the Whole Value (as)
pattern as name matches what pattern matches and also binds the whole
value to name. It tests a shape and keeps the value in one place:
type Tok {
TEof,
TNum(Int),
}
type Token {
tok: Tok,
pos: Int,
}
fn first(tokens: List(Token)) -> String {
match tokens {
[Token { tok: TEof, .. } as t, ..] -> "end of input at {t.pos}"
[Token { tok: TNum(n), .. }, ..] -> "number {n}"
[] -> "nothing"
}
}
fn main() {
println(first([Token { tok: TEof, pos: 4 }])) -- end of input at 4
println(first([Token { tok: TNum(7), pos: 1 }])) -- number 7
}open in playgroundIt stands anywhere a pattern can: in a match arm, inside another
pattern, in a let, a when let and a parameter.
fn main() {
let (a, b) as pair = (1, 2)
println("{a} {b} {pair}") -- 1 2 (1, 2)
let swap = { (x, y) as p -> "{p} becomes ({y}, {x})" }
println(swap((3, 4))) -- (3, 4) becomes (4, 3)
}open in playgroundas stands behind a pattern that tests or binds something. Behind a bare
name or _ (x as y, _ as z), or behind another as, a name already
binds the whole value, and it is an error: write z. So is as behind
a pattern made only of _ and .., which matches every value of its
type and binds no name: (_, _) as t, [..] as l and P { .. } as p
are t, l and p. [_, _] as l tests the length and stays.
An or-pattern stands in parentheses in front of the as, which then
names the value whichever alternative matched: (0 | 1) as bit. Written
without them, 0 | 1 as bit is an error, as is 0 as bit | 1: an
alternative that has a name of its own stands in parentheses too, and
every alternative binds the same names, (Circle(r) as s) | (Ring(r) as s).
fn describe(n: Int) -> String {
match n {
(0 | 1) as bit -> "the bit {bit}"
2..9 as digit -> "the digit {digit}"
other -> "{other}"
}
}
fn main() {
println(describe(1)) -- the bit 1
println(describe(7)) -- the digit 7
}open in playgroundGuards
match n {
0 -> "zero"
x when x > 0 -> "positive"
_ -> "negative"
}
Guard expressions are checked after the pattern matches. Pattern bindings are available in the guard.
A guard that is the literal true tests nothing, and an arm whose guard
is the literal false never runs: both are warnings (W0304), as such
conditions of a match without a scrutinee are. Like any arm with a guard,
an arm when true covers no value, so a match whose last arm is
_ when true does not cover every value; when the arms would cover
every value without such guards, the error’s help says to remove them.
An arm behind one that takes every value is warned as an arm that never
matches (W0303), and its guard is not warned again.
A guard on an or-pattern is tried with each alternative that matches, in
order, until one passes: (x, _) | (_, x) when x > 3 on (1, 5) takes
the arm with x = 5.
Range Patterns
Inclusive numeric ranges:
match score {
90..100 -> "A"
80..89 -> "B"
70..79 -> "C"
_ -> "F"
}
Float ranges work too: 0.0..1.0 matches value >= 0.0 && value <= 1.0.
A range whose start is greater than its end, such as 5..1, matches no
value and is an error.
Pin Operator (^)
Matches against the value of an existing variable instead of creating a new binding:
let expected = 42
match input {
^expected -> "got the expected value"
other -> "got {other} instead"
}
The variable is one from outside the pattern. A name the pattern binds
itself is not it: (x, ^x) compares the second element with an x bound
before the match, and is an error when there is none.
A pin compares as == does: the value’s type has Equal. A function has
none, so pinning one is an error at the pin (the pin '^f' requires a comparable type, got 'Fn(Int) -> Int'); a channel is equal to itself
only, and is pinned as below.
Works in any pattern position. Common with channel.select:
match channel.select([channel.Recv(ch1), channel.Recv(ch2)]) {
channel.Received(^ch1, Some(msg)) -> handle_first(msg)
channel.Received(^ch2, Some(msg)) -> handle_second(msg)
_ -> panic("unexpected")
}
when let/else for Inline Assertions
Asserts a pattern match and binds on success, or diverges on failure:
fn process(input) {
when let Ok(value) = parse(input) else {
return Err("parse failed")
}
when let Admin(perms) = user.role else {
return Err("unauthorized")
}
do_admin_thing(value, perms)
}
The else block must diverge: end it with return, panic or a call
of a function that returns Never; to go on with a function that calls
itself, write return f(...). A boolean form
(when cond else { ... }) also exists for flat guard sequences, and both
forms can be mixed.
See Error Handling for
the full treatment, including when to reach for when let-else instead
of ?.
Exhaustiveness Checking
The compiler checks that your match covers all possible cases. Missing a
variant produces a compile-time error. Since silt has no if, every choice
between values is a match, and every one of them is checked.
The check looks inside patterns: the fields of constructors, tuples and records, the elements of list patterns, the alternatives of or-patterns. Arms may split a value any way they like, as long as together they leave nothing out:
fn describe(xs: List(Option(Int))) -> String {
match xs {
[] -> "empty"
[None, ..] -> "starts with nothing"
[Some(n)] -> "just {n}"
[Some(n), _, ..] -> "{n} and more"
}
}
fn main() {
println(describe([Some(1), None]))
}open in playgroundAn arm with a guard may not be taken, so it covers nothing. Int literals
and ranges cover the numbers they hold, so arms that hold every Int
between them cover Int (-9223372036854775808..-1 and
0..9223372036854775807). Float and string literals, Float ranges, pins
and map patterns never cover their type between them: a match on such a
value needs an arm that takes every value (_ or a name).
An arm that never matches is a warning (W0303): the arms before it
without a guard take every value it would, as an arm behind _ or a
name, a literal written a second time, or an arm the arms before it
cover between them. So is an alternative of an or-pattern that the
alternatives or arms before it take (Some(_) | Some(1)). Such an arm is
never compiled, and is the usual sign of arms in the wrong order:
fn describe(n: Int) -> String {
match n {
_ -> "a number"
0 -> "zero" -- warning: this arm never matches: the arm at 3:5 takes every value it would
}
}
A match with so many interdependent patterns that the check cannot finish
is an error too (“could not verify that the match is exhaustive”); a _
arm settles it.
Trade-off: no if. A two-way choice takes four lines (match {, two
arms, }) where an if could take one. Longer choices and chains cost the
same as with if/else if, and when-else covers the early exit.