DocsLanguage Reference
Patterns
Every pattern form, where patterns may be written, and how they bind.
A pattern describes the shape of a value: it either matches the value or does not, and when it matches it may bind parts of the value to names. Patterns appear in match arms, in if case, guard case and while case conditions, in catch clauses, in for loops and in destructuring let and var bindings. This chapter lists every pattern form, where each may be written, how names are bound, and how the compiler checks that a match covers every value.
The guide teaches patterns in Pattern Matching.
Pattern = OrPattern ;OrPattern = OptionalPattern { "|" OptionalPattern } ;(* 'let v?' is '.Some(let v)': the pattern, matched against what an optional holds. *)OptionalPattern = PrimaryPattern { "?" } ;PrimaryPattern = WildcardPattern | BindingPattern | LiteralPattern | RangePattern | TuplePattern | UnionCasePattern | RecordPattern | ArrayPattern | TypeTestPattern | "(" Pattern ")" ;Where patterns appear#
| Place | Syntax | Patterns allowed |
|---|---|---|
match arm |
case pattern, pattern where guard => … |
Any |
if condition |
if case pattern = value { … } |
Any |
guard condition |
guard case pattern = value else { … } |
Any |
while condition |
while case pattern = value { … } |
Any |
catch clause |
catch pattern where guard { … } |
Any, matched against the error |
for loop |
for pattern in sequence { … } |
Binding patterns only |
let / var binding |
let pattern = value |
Binding patterns only |
A pattern that matches every value of its type is irrefutable: a name, _, and tuples and records made of irrefutable patterns. for loops and let or var bindings take only these — the binding patterns — since there is nowhere for a failed match to go. Everywhere else a pattern may be refutable: it may fail to match, and the construct then moves on (to the next arm or catch, the else, or the end of the loop).
switch cases take expressions compared by ==, not patterns; see Statements.
if case .Circle(let r) = shape { print(r) }guard case .Ok(let value) = outcome else { return }while case [let head, ...] = pending { pending = handle(head) }for (name, score) in results { print("\(name): \(score)") }let (q, r) = divmod(17, 5)Wildcard pattern#
WildcardPattern = "_" ;_ matches any value and binds nothing.
match point { case (0, _) => print("on the y-axis") case _ => print("elsewhere")}Binding patterns#
BindingPattern = [ "let" | "var" ] Identifier | TuplePattern | RecordPattern ;A name matches any value and binds it. let name binds an immutable name, var name a mutable copy. In a match arm or a condition, a bare name with no let binds too: case [first, _, last] binds first and last. let self is allowed, in guard let self.
match reading { case let x where x > 100 => print("high: \(x)") case var x => { x += 1 print(x) }}Binding rules.
- A name is bound only in the code the match guards: the arm's
whereclause and body, theiforwhileblock, or — forguard— the rest of the enclosing block. - A name in a pattern shadows one of the same name from an enclosing scope.
- A binding takes the type of what it matches. In a
match, a bare binding after earlier arms binds what those arms left of the subject:case let vaftercase noneis the unwrapped value. - A rest
...let namein an array pattern binds a slice,T[:], of the elements it matched.
Literal patterns#
LiteralPattern = Literal | "-" NumericLiteral ;A literal pattern matches a value equal to the literal: an integer, a float, a character, a string, true, false or none. A negative number is written - followed by a numeric literal; nothing else may follow the -.
match code { case 0 => "ok" case -1 => "failed" case _ => "unknown"}match command { case "start" | "go" => run() case "stop" => halt() case _ => usage()}Range patterns#
RangePattern = Expression ( "..." | "..<" ) Expression | ( "..." | "..<" ) Expression | Expression ( "..." ) ;A range pattern matches a value within the range. Its bounds are literals.
| Pattern | Matches |
|---|---|
a...b |
a through b |
a..<b |
a up to but not including b |
...b, ..<b |
Anything up to b (inclusive, exclusive) |
a... |
a and anything greater |
A half-open range needs its upper bound: 5..< alone is an error (write 5...).
let grade = match score { case 90...100 => "A" case 80..<90 => "B" case ..<80 => "C" case _ => "invalid"}Tuple patterns#
TuplePattern = "(" [ Pattern { "," Pattern } ] ")" ;A tuple pattern matches a tuple of the same count whose elements match the element patterns. A single pattern in parentheses is just that pattern. Matching several values at once is matching a tuple of them:
match (previous, next) { case (.None, .None) => .equal case (.None, _) => .less case (_, .None) => .greater case (.Some(let x), .Some(let y)) => compare(x, y)}Union case patterns#
UnionCasePattern = [ QualifiedName ] "." Identifier [ "(" [ SubPattern { "," SubPattern } ] ")" ] ;SubPattern = [ Identifier ":" ] Pattern ;A union case pattern matches a value of that case, and its payload against the sub-patterns. The union's name may be written, Shape.Circle, or left to the subject's type, .Circle. An enum's cases are matched the same way, without a payload.
match shape { case .Circle(let r) => Pi * r * r case .Rect(width: let w, height: let h) => w * h case .Poly(let points) where points.count < 3 => 0 case Shape.Poly(let points) => area(of: points) case .Empty => 0}- Sub-patterns match the payload's fields in order, or by label (
width: let w). Labels may be left out. - Writing the case with no parentheses matches it whatever its payload.
- Patterns nest:
case .Some(.Ok(let v)). - In a
catchclause, the error type is the subject:catch .NotFound(let path), or qualified,catch IoError.AlreadyExists(_).
Optional patterns#
pattern? matches an optional that holds a value matching pattern: let v? is .Some(let v). none (a literal pattern) matches the empty optional. ? may be repeated for nested optionals.
let first = match values { case let v? => v case none => 0}Record patterns#
RecordPattern = QualifiedName "{" [ FieldPattern { "," FieldPattern } ] "}" ;FieldPattern = Identifier [ ":" Pattern ] ;A record pattern matches a struct value by its fields. field: pattern matches a field against a pattern; a field named alone binds it under its own name. Fields not named are not examined.
match point { case Point { x: 0, y: let y } => print("on the y-axis at \(y)") case Point { x, y } => print("at \(x), \(y)")}In a destructuring binding the type name may be left out, since the value's type is known: let { name, age } = person, and with a rename, let { name: n } = person. (The grammar's RecordPattern requires the name; the parser accepts it without.)
Array patterns#
ArrayPattern = "[" [ ArrayPatternElem { "," ArrayPatternElem } ] "]" ;ArrayPatternElem = Pattern | "..." [ "let" Identifier ] ;An array pattern matches an array (of any kind) or a slice by its elements. Without a rest it matches only arrays of exactly that count. ... matches any number of elements in its place, and ...let name binds them, as a slice.
match tokens { case [] => print("empty") case [let only] => print("one: \(only)") case [first, _, last] => print("three, from \(first) to \(last)") case [let head, ...let tail] => print("\(head) then \(tail.count) more")}Type-test patterns#
TypeTestPattern = "is" Type | "let" Identifier "as" Type ;is T matches a value whose type is T, or conforms to or inherits from it. let name as T does the same and binds the value, as a T. They match against what an existential holds, a class instance's dynamic type, or a structural union's case; of an optional, they ask about the value it holds (none is no T).
fn describe(_ value: Int | String | Bool) -> String { return match value { case is Int => "a number" case let s as String => "the text \(s)" case _ => "a flag" }}Or-patterns#
p | q matches when either alternative does. Alternatives are most useful when they bind nothing, as here. Several patterns separated by , in a match arm are alternatives in the same way:
match c { case 'a' | 'e' | 'i' | 'o' | 'u' => .vowel case 'y', 'w' => .sometimes case _ => .consonant}Guards#
A match arm or a catch clause may add where condition after its patterns. The arm is taken only if the patterns match and the condition, which may use the pattern's bindings, is true.
Inside a where clause, a trailing identifier => is read as the arm's arrow, not as a closure with one parameter: case .Busy(let t) where t > limit => retry() means what it says. Parenthesise a closure that is genuinely wanted there.
Exhaustiveness#
A match must cover every value of its subject's type; one that does not, and has no default (or case _), is an error (S6003) that names a value it misses. An arm that earlier arms already cover can never run, and is warned of (S6006).
Both are checked by the usefulness algorithm of Maranget's Warnings for pattern matching, the one Rust uses. A pattern is useful after a list of earlier arms if it matches some value none of them match. An arm is redundant when none of its patterns is useful after the arms before it; the match is exhaustive when a wildcard is not useful after all of them. When a pattern is useful, the algorithm also produces a witness — a concrete value matched by nothing so far — which is what the diagnostic shows:
error[S6003]: match is not exhaustive --> src/shape.sb:12:11 |12 | match s { | ^ pattern '.Poly(_)' not coveredThe rules the checker follows:
- Finite types are covered case by case.
Bool, enums, unions, optionals, structural unions, tuples and records (one constructor each), and arrays (one constructor per length that matters, plus "longer") can be covered without a wildcard. Nested patterns, or-patterns and rests are handled at every depth. - Integers are covered by intervals. Every literal and range in a column cuts the type's domain into pieces, so
0..<10and10...255together cover aU8. - Other literals never cover. Strings, floats and characters, and type tests against open types, have unboundedly many values; a
matchon them needs adefault. - A guarded arm covers nothing, since its guard may fail; it is still checked for redundancy.
- A
@flagsenum always needs adefault: its values are sets of cases. - Another module's public union that is not
@frozenmay gain cases, so naming every case it has today does not cover it; the match needs adefault. A@frozenunion, and any union of your own module, does not.
The compiler offers a fix that adds the missing arms.