DocsLanguage Guide
Pattern Matching
match as a statement and an expression, every pattern form, guards and exhaustiveness.
A pattern describes the shape of a value: "a circle, and call its radius r", "a pair whose first element is zero", "an array with at least one element". Sable's match compares a value against a list of patterns in order, runs the arm of the first one that fits, and binds the names that pattern introduces.
You met match briefly in Enums and Unions, as the way to take a union apart. This chapter covers it fully: match as a statement and as an expression, how Sable proves a match is exhaustive, every pattern form, where guards, and the places outside match where patterns are also written — if case, guard case and while case.
Matching with match#
A match statement names a subject, then lists arms. Each arm is case, one or more patterns, =>, and a body:
union Shape { Circle(radius: F64) Rect(width: F64, height: F64) Empty}fn describe(_ shape: Shape) { match shape { case .Circle(let r) => print("a circle of radius \(r)") case .Rect(let w, let h) => print("a \(w) by \(h) rectangle") case .Empty => print("nothing") }}describe(.Rect(width: 3, height: 4))// prints a 3.0 by 4.0 rectangleSable tries the arms from top to bottom and runs the first one whose pattern fits. Only one arm runs: there is no fallthrough from one arm into the next, and no break is needed to stop it.
An arm's body may be a single expression, as above, or a block in braces when it needs several statements:
match shape { case .Circle(let r) => { let area = 3.14159 * r * r print("area \(area)") } case .Rect(let w, let h) => print("area \(w * h)") case .Empty => { }}{ } is an arm that does nothing.
Statement-form arms#
An arm may also use a colon instead of =>, followed by statements up to the next case or default. This reads like a C# switch section, and is convenient when each arm is a few statements that end by leaving the function:
fn sign(_ n: Int) -> Int { match n { case 0: return 0 case let m where m > 0: return 1 default: return -1 }}The colon form changes only the layout. It still runs one arm and never falls through; for C-style fallthrough on integers and enums, Sable has a separate switch statement, covered in Control Flow. match is the preferred form.
match as an expression#
match is also an expression. Written where a value is wanted, each arm's body gives the value of the whole match:
fn area(_ shape: Shape) -> F64 { return match shape { case .Circle(let r) => 3.14159 * r * r case .Rect(let w, let h) => w * h case .Empty => 0 }}Every arm must give a value, and all of the same type. An arm whose body is { }, or whose value is of a different type, is an error (S6007):
error[S6007]: this arm gives 'Int' but earlier arms gave 'String'An arm that leaves instead of giving a value — by throw, return, break or continue — is fine in a match expression. It contributes no type, because it never finishes (see Leaving from an arm).
Exhaustiveness#
A match must handle every possible value of its subject. Sable checks this at compile time, and when a case is missing it tells you which one with a concrete example, called a witness:
fn perimeter(_ shape: Shape) -> F64 { return match shape { case .Circle(let r) => 2 * 3.14159 * r case .Rect(let w, let h) => 2 * (w + h) }}error[S6003]: match is not exhaustive --> src/shape.sb:2:18 | 2 | return match shape { | ^ pattern '.Empty' not covered |help: add a case, or 'default => ...'The checker is the usefulness algorithm from Maranget's Warnings for pattern matching, the one Rust uses. It understands nested patterns, ranges, alternatives and array patterns with a rest, so the witness can be something like .Some(.Rect(_, _)) or [_, _, ...] — a value you can read straight off the message and add an arm for.
Exhaustiveness is checked for every subject type:
- A
Boolneedstrueandfalse. - An enum needs each of its cases. A
@flagsenum's value may be any combination of its flags, so amatchon one always needs adefault. - A union needs each case, with every payload covered.
- An optional needs a value and
none. - A structural union like
Int | Stringneeds each of its types. - Integers, floats, strings and arrays have too many values to list, so a
matchon one ends with a pattern that covers the rest.
default and case _#
Two arms cover everything that is left. default => … is the catch-all arm. case _ => … is the wildcard pattern used as an arm, and does the same. case let other => … covers everything too, and also names the value.
fn isRound(_ shape: Shape) -> Bool { return match shape { case .Circle(_) => true default => false }}Prefer listing the cases where there are few: if someone adds a case to Shape later, a match without default stops compiling and shows you every place that needs to handle it, while a default silently absorbs the new case.
Unreachable arms#
An arm that can never run, because the arms above it already cover everything it would match, is an error (S6006). This catches a repeated case, an arm written after default, or a default after arms that already covered every case:
match shape { case .Circle(_) => print("round") case .Rect(_, _) => print("square-ish") case .Empty => print("nothing") default => print("other") // error[S6006]: every value is already matched}Patterns#
The rest of this chapter goes through every pattern form. Patterns nest freely: wherever a pattern is expected, any of them may be written, so a union case's payload may hold a tuple pattern that holds a range.
A pattern is checked against the type of what it matches. A literal of the wrong type (case 1 against a Shape), an unknown union case or record field, or a payload with the wrong number of elements are all errors (S6000, S6001, S2002 and S6002).
The wildcard pattern#
_ matches any value and binds nothing. Use it for the parts of a value you don't care about:
match shape { case .Rect(_, 0) => print("a flat rectangle") case _ => print("something else")}Literal patterns#
A literal — an integer, a float, a string, a character, true or false — matches a value equal to it. A negative number is written with its sign:
fn describe(temperature: Int) -> String { return match temperature { case -40 => "the same in both scales" case 0 => "freezing" case 100 => "boiling" default => "\(temperature) degrees" }}none is a literal pattern too: it matches an optional that holds nothing (see Optional patterns).
Alternatives#
An arm may list several patterns separated by commas. The arm runs when any of them matches:
fn kind(_ c: Char) -> String { return match c { case 'a', 'e', 'i', 'o', 'u' => "vowel" case ' ', '\t', '\n' => "space" default => "other" }}Alternatives may also be written with |, which is a pattern in its own right and so may appear inside another pattern:
fn command(_ word: String) -> String { return match word { case "q" | "quit" | "exit" => "leave" case "h" | "help" => "show help" default => "unknown" }}Range patterns#
A range matches a value that lies inside it. Both kinds of range work, and either end may be left open:
fn grade(_ score: Int) -> String { return match score { case 90... => "A" case 80..<90 => "B" case 70..<80 => "C" case ..<70 => "fail" default => "fail" }}90... is every score from 90 up, and ..<70 every score below 70. Ranges need values that can be compared with the bounds; a range pattern against a String subject is an error (S6000).
Binding patterns#
let name matches any value and binds it to name for the arm's body. On its own it is irrefutable — it always matches — so case let x covers everything:
match readings.count { case 0 => print("no readings") case let n => print("\(n) readings")}Bindings are most useful inside other patterns, as .Circle(let r) shows. The same name may not be bound twice in one pattern (S2000).
Tuple patterns#
A tuple pattern matches a tuple element by element. Each element is a pattern of its own, so wildcards, literals and bindings mix:
fn locate(_ point: (Int, Int)) -> String { return match point { case (0, 0) => "at the origin" case (let x, 0) => "on the x-axis at \(x)" case (0, let y) => "on the y-axis at \(y)" case (-2...2, -2...2) => "near the origin" case (let x, let y) => "at (\(x), \(y))" }}print(locate((1, -1)))// prints near the originThe pattern must have as many elements as the tuple (S6000 otherwise).
Union case patterns#
A union case pattern is the case name with a leading dot, and a pattern for each payload element in parentheses. The type is known from the subject, so the dot form is enough; Shape.Circle(let r) is also accepted.
union Message { Text(from: String, body: String) Image(from: String, width: Int, height: Int) Ping}fn preview(_ m: Message) -> String { return match m { case .Text(let from, let body) => "\(from): \(body)" case .Image(let from, 0, _) => "\(from) sent an empty image" case .Image(let from, _, _) => "\(from) sent an image" case .Ping => "ping" }}Payload elements may be matched by label as well as by position. A labelled sub-pattern says which element it is, which reads better when a payload has several of the same type:
match m { case .Image(from: let sender, width: let w, _) where w > 4000 => print("a large image from \(sender)") default => { }}Nested patterns#
Because a payload's patterns are patterns, cases nest. Here an optional holds an Outcome, which holds a value:
union Outcome<T, E> { Ok(T) Err(E)}fn report(_ last: Outcome<Int, String>?) -> String { return match last { case .Some(.Ok(let v)) => "succeeded with \(v)" case .Some(.Err(let e)) => "failed: \(e)" case .None => "has not run" }}Record patterns#
A record pattern takes a struct apart by field name, written like a record literal with patterns for values. Fields you leave out aren't matched:
struct Point { var x: Int var y: Int}fn onAxis(_ p: Point) -> String { return match p { case Point { x: 0, y: 0 } => "origin" case Point { x: 0, y: let y } => "on the y-axis at \(y)" case Point { y: 0 } => "on the x-axis" default => "elsewhere" }}The type name comes first, as in a record literal. Each field must exist (S2002), and its pattern must fit the field's type (S6000).
Optional patterns#
An optional is the union Optional<T>, whose cases are .Some(T) and .None, so those case patterns work on it. The idiomatic spellings are shorter: let v? matches an optional that holds a value and binds the value, and none matches one that holds nothing:
fn greeting(_ name: String?) -> String { return match name { case let n? => "Hello, \(n)!" case none => "Hello, whoever you are." }}? after any pattern means "an optional holding something that matches this", so case 0? matches an Int? that holds zero. Optionals covers optionals fully.
Type-test patterns#
When the subject's type has more than one possible dynamic type — a structural union, an any P existential, a class with subclasses — a pattern can test the type. is T matches a value of type T; let name as T matches one and binds it, already converted to T:
fn render(_ value: Int | String | Bool) -> String { return match value { case let n as Int => "the number \(n)" case let s as String => "the text \"\(s)\"" case is Bool => "a flag" }}A structural union is closed, so a match that tests each of its types is exhaustive without a default. An existential or a class hierarchy is open — more types may conform or subclass later — so a match on one needs a default. Testing for a type the value could never have is an error (S3066). Casts and type tests outside patterns are in Casting, Metatypes and Reflection.
Array patterns#
An array pattern matches an array (or a slice) by its elements. Without a rest, it matches arrays of exactly that length:
fn summary(_ scores: Int[]) -> String { return match scores { case [] => "no scores" case [let only] => "one score: \(only)" case [let first, _, let last] => "three scores, from \(first) to \(last)" case [let head, ...let tail] => "\(head), then \(tail.count) more" }}print(summary([7, 3, 9, 4]))// prints 7, then 3 more... matches any number of elements, including none, and may be written alone ([let first, ...]) or with a binding (...let tail), which binds the elements it covered as a slice. An array pattern with a rest covers every array at least as long as the elements around it, so the last arm above makes summary exhaustive. Each element pattern must fit the array's element type (S6000).
String patterns#
A string is matched by string literals, often several at once:
fn isAffirmative(_ answer: String) -> Bool { return match answer { case "y" | "yes" | "ok" => true default => false }}Guards with where#
An arm may add a condition after its pattern with where. The arm runs only if the pattern matches and the condition is true; the condition may use the names the pattern bound:
fn classify(_ shape: Shape) -> String { return match shape { case .Circle(let r) where r > 100 => "a big circle" case .Circle(_) => "a circle" case .Rect(let w, let h) where w == h => "a square" case .Rect(_, _) => "a rectangle" case .Empty => "nothing" }}The condition must be a Bool (S3004). A guarded arm never counts towards exhaustiveness, because Sable can't know when the condition holds; that's why classify still has an unguarded arm for each case. Remove case .Circle(_) and the match is no longer exhaustive, even though the guard r > 100 is just one test.
=> after a where clause#
The => that ends a where condition is always the arm's arrow. Elsewhere, t => … would be a one-parameter closure; inside a guard it isn't, so this reads as you'd expect:
match task { case .Busy(let t) where t > limit => retry() default => { }}If you really do want a closure inside the condition, put it in parentheses.
Matching several values at once#
To match on two or more values together, put them in a tuple and match tuple patterns. This replaces nested matches and makes the combinations explicit:
Ordering here is the standard library's enum of .Less, .Equal and .Greater:
fn compareOptional(_ a: Int?, _ b: Int?) -> Ordering { return match (a, b) { case (none, none) => .Equal case (none, _) => .Less case (_, none) => .Greater case (let x?, let y?) => x < y ? .Less : x > y ? .Greater : .Equal }}Exhaustiveness is checked over the combinations: drop case (_, none) and the error names the pair that is no longer covered, a value and none.
Leaving from an arm#
An arm's body may be a return, break, continue or throw statement written directly after =>. case .Some(let r) => return r means the same as case .Some(let r) => { return r }:
fn firstNegative(_ readings: Int[]) -> Int? { for r in readings { match r { case ..<0 => return r case 0 => continue default => print("reading \(r)") } } return none}In a match expression, such an arm gives no value — its type is Never, which fits any type — so the other arms decide the type of the whole expression:
union ShapeError { NoSize }fn width(_ shape: Shape) throws(ShapeError) -> F64 { return match shape { case .Circle(let r) => 2 * r case .Rect(let w, _) => w case .Empty => throw ShapeError.NoSize }}throw as an expression is covered in Error Handling.
Patterns in conditions#
match is not the only place patterns are written. When you care about only one pattern, if case tests a value against it and binds its names in the body:
if case .Circle(let r) = shape { print("radius \(r)")}The pattern comes first, then =, then the value. A case condition may be combined with other conditions, separated by commas, just like if let (see Control Flow):
if case .Image(let from, let w, let h) = message, w * h > 1_000_000 { print("a large image from \(from)")}guard case does the opposite: it leaves the scope unless the pattern matches, and its bindings stay in scope after the guard:
fn radius(of shape: Shape) -> F64 { guard case .Circle(let r) = shape else { return 0 } return r}while case repeats its body as long as the pattern matches, rebinding each time:
var pending: Int[>..] = [3, 1, 2]while case [_, ...] = pending { print(pending.removeLast())}// prints 2, then 1, then 3Patterns in declarations#
let and var take patterns too, but only ones that always match: tuples of bindings and wildcards, and record patterns that take a struct apart by field name.
let (q, r) = (17 / 5, 17 % 5)let { x, y } = Point { x: 3, y: 4 }let { x: across } = Point { x: 3, y: 4 } // renamedA pattern that might not match, such as let (1, label) = pair(), is an error (S6009); the diagnostic suggests if case instead, which says what should happen when it doesn't.
Narrowing structural unions#
A structural union like Int | String | Vec3 (from Enums and Unions) can be narrowed without a match. After a test with is, Sable treats the value as the narrower type wherever the test is known to hold:
struct Vec3 { var x: F64 var y: F64 var z: F64}fn render(_ v: Int | String | Vec3) -> String { if v is Int { return "the number \(v)" } // v is an Int here if v is String { return v } // and a String here return "(\(v.x), \(v.y), \(v.z))" // only a Vec3 is left}Narrowing is flow-sensitive. Inside if v is Int { … }, v is an Int; after an if that leaves when the test holds, the rest of the function knows the value is one of the remaining types. Narrowing ends at the end of the block it was made in, and is undone by assigning to the variable. A test that does not leave narrows nothing for the code after it.
match with let x as T arms, if let, and comparing with none (for a union that includes None, see Optionals) all narrow in the same way.
Matching across modules#
A public union may gain cases in a later version of its library. If code in another module matched it exhaustively without a default, adding a case would break that code. So Sable requires a default when you match a public union from another module.
A library that promises a union will never gain a case marks it @frozen. Other modules may then match it exhaustively, with no default:
@frozenpublic union JsonNumber { Integer(I64) Real(F64)}Optional is @frozen, which is why a match on T? needs only a value arm and a none arm. Inside the module that declares a union, you never need a default: when you add a case, the compiler shows you every match to update. Modules and Access Control has more on library evolution.