10. Patterns
Taught in Pattern Matching.
Where patterns appear
Section titled “Where patterns appear”A pattern stands in a case arm (§8 case), a pattern if (§8
if/else), a binding (§6), a binding with else (Bindings with
else), an assert (§17), an is test (§8 Pattern test: is), a
function or lambda parameter (§7 Parameter Destructuring), a test’s setup
binding and a subtests row (§17).
A pattern is refutable when some value of its type does not match it, and irrefutable when every value does.
- A
casearm, a patternif, a binding withelse, anassertand anistest take any pattern. - A plain binding, a parameter, a lambda parameter, a test’s setup binding and
a
subtestsrow take an irrefutable pattern. A refutable one in a binding is the errorthis pattern can fail to match a value of type Maybe<Int>; add `else` to handle a value it does not match, or match it with `case` or `if Pattern = expr`, and in a parameterrefutable pattern in parameter; bind the parameter and use a `case` in the body. - Irrefutable patterns are names,
_, tuple, struct and distinct patterns whose parts are irrefutable, a single-variant enum’s variant, and anorpattern whose alternatives together cover the type (Exhaustiveness checking).
A name in a pattern binds the matched value. A name that starts with _ is a
discard and binds nothing. A pattern binds each name once: Some(n) as n is
`n` is bound twice in one pattern; give each binding its own name.
A name never compares, even when it names a value in scope. In a pattern that
may fail to match (a case arm, a pattern if, a binding with else, an
else arm and an assert), a name that names a once visible there, declared
in the file or imported, is an error at the name, since it would match every
value: with once not_found = 404, an arm not_found -> ... of
case code is
this binds a new `not_found`, which matches every value; `not_found` is a `once`, with the help to compare with it, write `code when code == not_found` . A local binding of the same name hides the once and the rule
does not apply, and neither does a discard name. A plain binding, a
parameter and a destructure without else bind new names by intent: there a
name may hide a once as it may any other name.
Literal patterns
Section titled “Literal patterns”A literal pattern (3, -1, 2.5, 1.50d, "a", 'a', True) matches a
value equal to the literal. The value must have the literal’s type, at any
depth. A literal never converts: an arm "a" -> ... over an Int is the
error pattern "a" is a String, but the value is an Int, and 3 does not
match a Float (write 3.0).
The constants are patterns too. True, False and None are variant
patterns (Variant patterns), and Unit matches the one value of type
Unit, so it covers its type: Ok(Unit) and Err(e) are exhaustive over a
Result<Unit, E>. Unit over a value of another type is the error
pattern Unit is a Unit, but the value is an Int.
Variant patterns
Section titled “Variant patterns”A variant pattern names the variant in the dot-leading form (.Circle,
.Circle{r:}, .Some(x)) or qualified by its enum (Shape.Circle,
Shape.Circle{r:}). Its payload pattern is written as the variant is built
(§4 Enums (Algebraic Data Types)).
enum Shape Circle {r: Float} Rect {w: Float, h: Float} Point end fn area(shape: Shape) -> Float case shape .Circle{r:} -> 3.14 * r * r .Rect{w:, h:} -> w * h .Point -> 0.0 end end fn main() dbg area(Shape.Rect{w: 2.0, h: 3.0}) // 6.0 end
- A
.Variantresolves against the scrutinee’s enum, by the outside-in walk of §4 Variant Resolution, with the scrutinee as the determining position. - A qualifier must name the scrutinee’s enum, or a module-qualified or imported
spelling of it. An unknown name is an error (
C6lor.Blueisunknown type "C6lor"), and so is another enum, even one with a variant of that name. - A bare variant name (
Circle,Circle{r:},Items[x, y],Named{"k" => v}) is accepted only for a prelude variant (Ok,Err,Some,None,True,False) or one an owner selector imports (import shape.Shape.{Circle}). Otherwise it is the errorbare variant 'Blue' in pattern position; use '.Blue' (or 'Color.Blue'). - A variant that carries data is matched with its payload written:
Some(_),Err(_),.Rect{}. A bareErris the errorvariant Err carries data; pattern needs an explicit payload (e.g. Err(_) or Err(name)). A payload of a type with one value is still data:Ping(Unit)is matched as.Ping(_). Only anembedsof a zero-sized type (embeds Expired) is matched bare.
Struct Destructuring
Section titled “Struct Destructuring”Type{field: pattern, ...} matches a struct. {field: pattern, ...}
matches a struct or an anonymous struct.
struct User name: String age: Int end fn describe(user: User) -> String case user User{name: "Alice"} -> "found Alice" User{name:, age:} when age > 18 -> "adult: ${name}" {age: years} -> "minor of ${years}" end end fn main() dbg describe(User{name: "Bo", age: 9}) // "minor of 9" end
- Matching is partial: fields left out are not tested.
field:alone binds the field to a name of the same name, andfield: patternmatches it against the pattern.- A written type name must name the value’s struct, directly or through a
typealias. A typed pattern does not match an anonymous struct:User{name:} = {name: "Ada"}is the errorstruct pattern names User, but the value is the anonymous struct {name: String}. - A pattern names each field once:
User{age: 1, age: a}isfield 'age' is given twice in this User pattern, and an anonymous one saysthis struct pattern. A punned repeat (User{age:, age:}) also bindsagetwice:`age` is bound twice in one pattern; give each binding its own name.
Tuple patterns
Section titled “Tuple patterns”(p1, p2, ...) matches a tuple of that many elements, each against its
pattern.
Distinct Type Destructuring
Section titled “Distinct Type Destructuring”A distinct type’s value is matched in the form it is built: Id(n) for a
distinct over a scalar, and for one over a tuple, map, vector or set either the
named literal pattern (Pair(a, b), Kvs{...}, Path[...], Tags[...])
or the call form (Pair((a, b)), Kvs({...})).
type Pair (Int, String) fn show(p: Pair) -> String case p Pair(a, b) -> "${a}, ${b}" end end fn first(p: Pair) -> Int Pair((a, _)) = p a end fn main() dbg show(Pair(1, "hello")) // "1, hello" dbg first(Pair(1, "hello")) // 1 end
The call form takes one value. For a tuple distinct, Pair(a) binds the whole
tuple to a, and Pair(a, b), one pattern per element, takes the tuple apart
with it.
A distinct declared in another module is named in a pattern as it is in a
literal, bare when imported or through its module: kinds.Items[a, b],
kinds.Kvs{"a" => v} and kinds.Pair(a, b) each take apart that module’s
type. The prefix names a type as an annotation does, and must be the value’s
type itself: another module’s type of the same name is a different type
(pattern names other.Items, but the value is a kinds.Items), and so is any
other type (pattern names kinds.Other, but the value is an Items).
List Destructuring
Section titled “List Destructuring”Taught in Pattern Matching.
A bracket pattern takes apart the collection its subject is: a list or a vector by position (this section and Vector Destructuring), a set by membership (Set Destructuring). The pattern has no symbol of its own, as a bracket literal has none (§3 Literal forms).
[p1, p2] matches a list of exactly that many elements. .. among the
elements matches any number of elements between those before it and those
after it.
fn describe(lines: List<String>) -> String case lines [] -> "empty" [only] -> "just ${only}" ["graph {", ..body, "}"] -> "a graph of ${Iter.count(body)} lines" [first, ..rest] -> "${first} and ${Iter.count(rest)} more" end end fn main() dbg describe(["graph {", "a", "b", "}"]) // "a graph of 2 lines" end
- One
... Elements before it match from the front and elements after it from the end. A second..is the parse errora list pattern takes one `..`. - What follows the
... At the end of the pattern,..takes a pattern for the rest, aList, or nothing. With elements after it, it takes a name or nothing ([first, ..mid, last],[1, .., 9]); anything else is the parse errora list pattern's `..` takes a name or nothing when elements follow it. - A bare
..ignores the rest..._is the parse errorwrite `..` to ignore the rest of a list pattern, not `.._`, over a list, a vector or a set. A labeled discard (.._rest) is allowed. - Cost. A rest at the end shares the list’s cells, so
[x, ..rest]takes no copy and a recursive walk over it is linear. Elements after the..take one walk to the list’s end, and a name for the middle (..mid) is a copy of those elements. - A list pattern is refutable. Coverage is by length (Exhaustiveness
checking):
[1, .., 3]can fail, so as a binding it takes anelse, and alone in acaseit isnon-exhaustive case on List<Int>: missing []. - Over a value that is no list, vector or set it is the error
list pattern requires a list, vector or set, got Int. +patterns are for strings only (String Prefix Patterns).
Vector Destructuring
Section titled “Vector Destructuring”Over a vector, [...] matches as it matches a list, from either end.
fn ends(v: Vector<Int>) -> Int case v [] -> 0 [only] -> only [first, .., last] -> first + last end end fn main() dbg ends([1, 2, 3]) // 4 end
- One
.., anywhere among the elements, followed by a name, which binds the elements between as aVector, or by nothing. Anything else after it isthe rest of a vector pattern is a name or nothing: `..rest` or `..`. - Without a
.., the pattern matches only vectors of its length:[a, b]matches a two-element vector and[]the empty one. - The rest shares the vector’s storage, so binding it takes no copy.
- A vector pattern is refutable, so as a parameter pattern it is the error
refutable pattern in parameter. Coverage is by length, as a list’s is:[]with[x]isnon-exhaustive case on Vector<Int>: missing [_, _, ..], and[1, .., 3]alone isnon-exhaustive case on Vector<Int>: missing []. - A type built on a vector names itself before the bracket, as its literal
does:
Path[a, .., z]for atype Path Vector<Int>, and.Items[x, ..]for a vector-payload variant. Over the type itself,[a, .., z]takes it apart too.
Map Destructuring
Section titled “Map Destructuring”{key => pattern, ...} matches a map that holds every key, each value
matching its pattern. Other keys are ignored. {} holds no key and matches
every map.
fn port(config: Map<String, Int>) -> String case config {"debug" => 1, "port" => p} -> "debug on ${p}" {"port" => p} -> "port ${p}" _ -> "no port" end end fn main() dbg port({"port" => 8080}) // "port 8080" end
- A key is an expression, evaluated in the scope before the pattern, as a map
literal’s key is. Any keyable value works (variants, tuples, structs), and a
key may be computed:
{target => v}matches the entry whose key equalstarget’s value. A key never sees a name the pattern itself binds: aftera = "host",{"mode" => a, a => b}looks up"host"forband binds the mode’s value toa. - The first entry’s
=>makes the braces a map pattern, asname:makes them a struct pattern (§3 Literal forms). - A missing key is a pattern that does not match, never a trap, since whether
a key is present is data the program does not control (§11 Traps,
MaybeandResult). - A map pattern never covers every map for the coverage check,
{}included, though{}matches every map. Acaseover a map needs a_arm (non-exhaustive case: add a `_` arm). - A binding with a map pattern takes an
else, every path of which leaves (Bindings withelse). Without one,{"port" => port} = configis the errorthis pattern can fail to match a value of type Map<String, Int>; add `else` ..., whose help isa map pattern does not match a map that lacks one of its keys. Handle a missing key with `else`, or read one key with `Map.get`, which returns a `Maybe`. In a test,assert {"port" => port} = configfails when a key is missing. - The same constant key twice (
{"k" => a, "k" => b}) is a compile error at the second,key `"k"` is given twice in this map pattern; match its value once(§3 Repeated keys). Keys equal only at run time both look up the one entry, and both patterns must match its value.
Set Destructuring
Section titled “Set Destructuring”Over a set, [e1, e2, ...] matches a set that holds exactly those
elements. With a .. at the end, the set may hold others too, and a name
after the .. binds them.
fn role(s: Set<String>) -> String case s ["admin", ..rest] -> "admin and ${Set.size(rest)} more" ["user", ..] -> "user" [] -> "nobody" _ -> "other" end end fn main() dbg role(["admin", "dev"]) // "admin and 1 more" end
- An element is a constant to look up, never a place to bind: a number,
string or codepoint literal, the value the set must contain.
[_, ..]is the erroran element of a set pattern is a constant the set contains, not a place to bind: `_` names no value; `..` matches the other elements, and[role, ..]is the same error, which saysrolewould bind a name and that a guard tests a value in scope:[..] when Set.contains(s, role). Another pattern there, a variant or a tuple, is the same error, which says to write a number, string or codepoint. - The
..comes last:[..rest, 1]over a set isset pattern `..` must be the last element. - A constant element is named once:
["a", "a", ..]iselement `"a"` is given twice in this set pattern; test it once. - Each element is checked against the element type (
set pattern element type mismatch: expected String, got Int). - A set pattern never covers every set. A
caseneeds a_arm, and a binding takes anelse, every path of which leaves. Without one, the binding’s help isa set pattern does not match a set that lacks one of its elements. Handle that with `else`, or test one element with `Set.contains`. - A type built on a set names itself before the bracket:
Tags["a", ..others].
String Prefix Patterns
Section titled “String Prefix Patterns”"prefix" + rest matches a string that begins with the literal’s bytes, and
binds rest to the remainder, so the string is "prefix" + rest.
fn route(path: String) -> String case path "/users/" + id -> "user ${id}" "/health" -> "ok" _ -> "not found" end end fn main() dbg route("/users/7") // "user 7" end
- The left side is a string literal without interpolation, and the right side a name. Only a prefix is matched.
- The rest may be empty, and may begin with a combining mark that follows the
literal’s last codepoint:
"e" + restagainst"e\u{301}"binds"\u{301}". - The pattern is refutable. It stands in a
casearm, a patternif, a binding withelse, or nested in another pattern (Some("/users/" + id)). Acaseneeds a_arm.
Guards
Section titled “Guards”Pattern when condition -> body runs the arm when the pattern matches and the
condition is True. Otherwise matching continues with the next arm. The
pattern’s names are in scope in the condition.
- A guard is a
Bool:n when n + 1 -> ...is the error`when` guard must be Bool, got Int. - In a guard,
oris the Boolean operator:.Circle{r:} when r < 1.0 or r > 9.0. - An arm with a guard never counts toward exhaustiveness.
- A guard narrows what it checks in the arm’s body, as an
ifcondition does its branch (§4 Narrowing): inn when n > 0 -> ...,nis aPositiveInt.
Alternatives: or
Section titled “Alternatives: or”Taught in Pattern Matching.
A or B matches a value that A or B matches.
enum Shape Circle {r: Float} Square {side: Float} Point end fn describe(shape: Shape) -> String case shape .Circle{r:} or .Square{side: r} when r > 10.0 -> "big, ${r} across" .Circle{r:} or .Square{side: r} -> "${r} across" .Point -> "a point" end end fn main() dbg describe(Shape.Square{side: 2.0}) // "2.0 across" end
- Every alternative binds the same names, each at one type. A name one
alternative lacks is the error
`r` is bound by `.A(r)` but not by `.P`; every alternative of an `or` pattern must bind the same names. A name bound at two types is`v` is an Int in `.N(v)` but a String in `.T(v)`; a name an `or` pattern binds has one type in every alternative. A discard name need not appear in every alternative. - A name an
orpattern binds is one binding: it is read, renamed and reported unused as one. - Alternatives are tried left to right, and the first that matches binds the names.
ornests inside any pattern that holds subpatterns: a payload (Some(.Equilateral or .Isosceles)), a tuple element ((0, x) or (x, 0)), a struct field, a list or vector element ([')' or ']' as c, ..rest]) and a map value. Alternatives may be literals (1 or 2 or 3,"yes" or "y").orbinds looser than every pattern construct butas. Parentheses group:(A or B) or CisA or B or C.- A guard applies to the whole arm. When it is
False, matching continues with the next arm, not the next alternative. - Coverage is the union of the alternatives.
orstands wherever a pattern does. Where the pattern must match every value, the alternatives must together cover the type:fn value(.L(n) or .R(n): Side)over a two-variantSideis accepted, andfn f(.Red or .Green: Color)over a three-variantColorisrefutable pattern in parameter; bind the parameter and use a `case` in the body.- In a binding with
else, a fallback stands in for one variant’s payload, soOk(.L(n) or .R(n)) = r else Side.L(0)takes a fallback and.A(n) or .B(n) = e else return 0must leave.
Naming the Whole Match: as
Section titled “Naming the Whole Match: as”Taught in Pattern Matching.
P as name matches P and binds the whole value P matched to name.
fn describe(result: Result<Int, String>) -> String case result Ok(n) as r when n > 9 -> "big: ${r}" Ok(_) -> "small" Err(msg) -> msg end end fn main() dbg describe(Ok(12)) // "big: Ok(12)" end
- Scope.
asbinds looser than every other pattern construct,orincluded. It names everything to its left in its position:Ok(x) as rbinds the wholeResult,Ok(T{kind: .A} as t)the payload, and"/u/" + id as paththe whole string.A or B as xnames the value whichever alternative matched. To name one alternative, parenthesize it:.A(n) as a or .B(n)is the parse erroran `as` names the whole `or` pattern, so it goes after the last alternative; to name one alternative, parenthesize it: `(P as a) or ...`. - The name is a binding name, not a pattern:
P as Bigis the parse errorexpected a binding name after `as` in a pattern, got "Big"; `P as name` binds the whole matched value to name.P as _andP as (r)are the same error, withgot "_"andgot "(". - Its type is the type of the position: the scrutinee’s at the top of an
arm, the payload’s inside a variant, the element’s inside a list, the field’s
inside a struct pattern.
Pdoes not narrow it:Ok(_) as rover aResult<Int, String>binds aResult<Int, String>. - It never changes what matches.
P as nameis refutable exactly whenPis. - It must add a name.
y as xis`y as x` binds the same value twice; use one name,P as a as bis`as a as b` binds the same value twice; use one name, and_ as xis`_ as x` matches every value, as `x` does; write `x`. - The name follows the rules of any pattern name: it is in scope in the guard
and body, may shadow, must be read unless it starts with
_. - In a binding with
else, anasaround the whole pattern rules out a fallback, since there is no value to bind it to:Some(n) as m = find() else 0is the no-single-payload error. Anasinside the payload is allowed:Ok((w, h) as size) = r else (80, 24).
Exhaustiveness checking
Section titled “Exhaustiveness checking”A case is exhaustive when its unguarded arms together match every value of
the scrutinee’s type. A case that is not is a compile error. The check works
component by component:
_and a name match everything.- An enum is covered when every variant is, and a variant when the arms naming
it cover its payload.
Some(Ok(_)),Some(Err(_))andNonecover aMaybe<Result<T, E>>. - A tuple, struct or distinct value is covered when its components are, taken together. A struct pattern that only binds fields covers the struct.
- A list or vector is covered by length.
[]and[head, ..tail]cover every list;[]and[x]miss lists of two or more. Elements after the..are tested against the last elements, so[],[_]and[_, .., _]cover every list, and[1, .., 3]covers nothing on its own.[..all]covers every list or vector. - A literal, a string prefix, a map pattern and a set pattern never cover their
type: the compiler does not enumerate
Int,Float,Decimal,String,Byte,Codepoint,MaporSet. Where one of those decides the match, some arm needs_or a name in that position. - An
orpattern covers what its alternatives cover together. - An arm with a
whenguard never counts. - A subject-less
caseneeds a_arm (§8case).
When the compiler can name a missing value it does: non-exhaustive case on Shape: missing Rect, non-exhaustive case on (Maybe<Int>, Maybe<Int>): missing (None, None), non-exhaustive case on List<Int>: missing [_, _, ..], non-exhaustive case on Vector<Int>: missing [_, _, ..]. When only a
value no list of literals can cover is missing, as in a case (n, n) whose
only arm is (0, 0) -> "zero", the error is non-exhaustive case: add a `_` arm.
Type Narrowing
Section titled “Type Narrowing”In a case arm whose pattern matches one embeds variant, the scrutinee’s
name has the embedded type.
struct Circle radius: Float end enum Shape embeds Circle Point end fn area(c: Circle) -> Float 3.14 * c.radius * c.radius end fn describe(value: Shape) -> Float case value .Circle{radius: _} -> area(value) // value is a Circle here .Point -> 0.0 end end fn main() dbg describe(Circle{radius: 1.0}) // 3.14 end
- What narrows is a name. The scrutinee must be a parameter or a local
binding written as a plain name (
case value, notcase w.shapeorcase load()). Every read of the name in the arm’s guard and body is the narrowed value, lambdas created there included. A name the arm rebinds is a new binding. - Where. A
casearm, and the first branch ofif Pattern = name, whose pattern matches oneembedsvariant:.Circle{radius:},Shape.Circle{radius: r}, and.Id(n)for an embedded distinctId. Anasaround the pattern narrows the name as it would without theas; theasname keeps the type of its position. - An
orpattern, a struct-shaped or positional variant that is not anembeds, theelsebranch, a binding withelseand a pipedcasenarrow nothing. - A narrowed value may still be passed where the enum is expected.
- A
value is Patterntest narrows nothing, in anifcondition or anywhere;if Pattern = nameis the form that narrows. A condition narrows a binding’s range, and so its std subtype, by its own rule (§4 Narrowing).
Bindings with else
Section titled “Bindings with else”Taught in Pattern Matching.
Pattern = value else ... binds the pattern’s names for the rest of the
enclosing block when the value matches, and runs the else when it does
not. The else takes one of two forms:
- Inline. Anything after
elseon its line is one expression, orbreak,continueorreturn:Some(address) = user else "none". - Below. An
elsethat ends its line takes the lines below, closed byend: case arms when the first line ispattern ->orpattern when, and an ordinary body otherwise.
The else stands on the binding’s line, or for a pattern that can fail it
may start the line after a value written over several lines.
fn first_word(words: List<String>) -> String [first, .._rest] = words else return "(none)" first end fn email(user: Maybe<String>) -> String Some(address) = user else "none" address end fn port(text: String) -> Result<Int, String> Ok(n) = String.to_int(text) |> Maybe.to_result("empty") else Err(e) -> return Err("bad port: ${e}") end Ok(n) end fn main() dbg first_word([]) // "(none)" dbg email(None) // "none" dbg port("80") // Ok(80) end
- The value is evaluated once. The pattern’s names are not in scope inside the
else. - Arms match the value that did not match, of the value’s type. The binding’s
pattern and the arms together must be exhaustive by
case’s rules (Exhaustiveness checking):non-exhaustive `else` on Result: missing Err. - Every path through the
elseeither leaves (return;breakorcontinuein an iteration callback, §9; a trap such asunreachable "reason"ortodo; a branch every path of which leaves) or produces a fallback. A path that traps binds none of the names. - A fallback is allowed only when the pattern names one variant with a
payload,
Variant(inner)or.Variant{fields:}, whose inner pattern always matches. The fallback has the payload’s type (for a struct-shaped variant, the anonymous struct of its fields), and the inner pattern binds from it as it would from a match:Ok((w, h)) = r else (80, 24)bindswto 80. A fallback of another type isthe fallback stands in for Some's payload of type String, got Int. - A pattern with no single payload (a bracket or map pattern, a
nested refutable pattern such as
Ok(Some(x)), a literal, a tuple with a refutable part) requires every path to leave. A path that produces a value is the errorthis pattern has no single payload a fallback could stand in for; every path through `else` must return, break or continue. - A pattern that always matches takes no
else:(x, y) = pair else returnisthis pattern always matches; remove the else. A single-variant enum’s pattern always matches: for anenum Onlywhose one variant isOne Int,Only.One(p) = onlyneeds noelse, and over a struct-shaped variant,Rec.Fields(r) = recbindsrto the anonymous struct of its fields. - A pattern that can fail requires one (Where patterns appear). On
Ok(x)over aResultorSome(x)over aMaybe, the help points at?: writex = ...?. - A
?inside theelseexits the enclosing function or lambda, andreturninside a lambda’selseexits the lambda.