Skip to content

10. Patterns

Taught in Pattern Matching.

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 case arm, a pattern if, a binding with else, an assert and an is test take any pattern.
  • A plain binding, a parameter, a lambda parameter, a test’s setup binding and a subtests row take an irrefutable pattern. A refutable one in a binding is the error this 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 parameter refutable 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 an or pattern 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.

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.

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 .Variant resolves 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.Blue is unknown 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 error bare 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 bare Err is the error variant 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 an embeds of a zero-sized type (embeds Expired) is matched bare.

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, and field: pattern matches 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 error struct pattern names User, but the value is the anonymous struct {name: String}.
  • A pattern names each field once: User{age: 1, age: a} is field 'age' is given twice in this User pattern, and an anonymous one says this struct pattern. A punned repeat (User{age:, age:}) also binds age twice: `age` is bound twice in one pattern; give each binding its own name.

(p1, p2, ...) matches a tuple of that many elements, each against its pattern.

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).

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 error a list pattern takes one `..` .
  • What follows the ... At the end of the pattern, .. takes a pattern for the rest, a List, or nothing. With elements after it, it takes a name or nothing ([first, ..mid, last], [1, .., 9]); anything else is the parse error a list pattern's `..` takes a name or nothing when elements follow it.
  • A bare .. ignores the rest. .._ is the parse error write `..` 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 an else, and alone in a case it is non-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).

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 a Vector, or by nothing. Anything else after it is the 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] is non-exhaustive case on Vector<Int>: missing [_, _, ..], and [1, .., 3] alone is non-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 a type Path Vector<Int>, and .Items[x, ..] for a vector-payload variant. Over the type itself, [a, .., z] takes it apart too.

{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 equals target’s value. A key never sees a name the pattern itself binds: after a = "host", {"mode" => a, a => b} looks up "host" for b and binds the mode’s value to a.
  • The first entry’s => makes the braces a map pattern, as name: 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, Maybe and Result).
  • A map pattern never covers every map for the coverage check, {} included, though {} matches every map. A case over 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 with else). Without one, {"port" => port} = config is the error this pattern can fail to match a value of type Map<String, Int>; add `else` ..., whose help is a 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} = config fails 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.

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 error an 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 says role would 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 is set pattern `..` must be the last element.
  • A constant element is named once: ["a", "a", ..] is element `"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 case needs a _ arm, and a binding takes an else, every path of which leaves. Without one, the binding’s help is a 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].

"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" + rest against "e\u{301}" binds "\u{301}".
  • The pattern is refutable. It stands in a case arm, a pattern if, a binding with else, or nested in another pattern (Some("/users/" + id)). A case needs a _ arm.

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, or is 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 if condition does its branch (§4 Narrowing): in n when n > 0 -> ..., n is a PositiveInt.

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 or pattern 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.
  • or nests 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").
  • or binds looser than every pattern construct but as. Parentheses group: (A or B) or C is A 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.
  • or stands 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-variant Side is accepted, and fn f(.Red or .Green: Color) over a three-variant Color is refutable 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, so Ok(.L(n) or .R(n)) = r else Side.L(0) takes a fallback and .A(n) or .B(n) = e else return 0 must leave.

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. as binds looser than every other pattern construct, or included. It names everything to its left in its position: Ok(x) as r binds the whole Result, Ok(T{kind: .A} as t) the payload, and "/u/" + id as path the whole string. A or B as x names the value whichever alternative matched. To name one alternative, parenthesize it: .A(n) as a or .B(n) is the parse error an `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 Big is the parse error expected a binding name after `as` in a pattern, got "Big"; `P as name` binds the whole matched value to name. P as _ and P as (r) are the same error, with got "_" and got "(".
  • 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. P does not narrow it: Ok(_) as r over a Result<Int, String> binds a Result<Int, String>.
  • It never changes what matches. P as name is refutable exactly when P is.
  • It must add a name. y as x is `y as x` binds the same value twice; use one name, P as a as b is `as a as b` binds the same value twice; use one name, and _ as x is `_ 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, an as around the whole pattern rules out a fallback, since there is no value to bind it to: Some(n) as m = find() else 0 is the no-single-payload error. An as inside the payload is allowed: Ok((w, h) as size) = r else (80, 24).

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(_)) and None cover a Maybe<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, Map or Set. Where one of those decides the match, some arm needs _ or a name in that position.
  • An or pattern covers what its alternatives cover together.
  • An arm with a when guard never counts.
  • A subject-less case needs a _ arm (§8 case).

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.

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, not case w.shape or case 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 case arm, and the first branch of if Pattern = name, whose pattern matches one embeds variant: .Circle{radius:}, Shape.Circle{radius: r}, and .Id(n) for an embedded distinct Id. An as around the pattern narrows the name as it would without the as; the as name keeps the type of its position.
  • An or pattern, a struct-shaped or positional variant that is not an embeds, the else branch, a binding with else and a piped case narrow nothing.
  • A narrowed value may still be passed where the enum is expected.
  • A value is Pattern test narrows nothing, in an if condition or anywhere; if Pattern = name is the form that narrows. A condition narrows a binding’s range, and so its std subtype, by its own rule (§4 Narrowing).

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 else on its line is one expression, or break, continue or return: Some(address) = user else "none".
  • Below. An else that ends its line takes the lines below, closed by end: case arms when the first line is pattern -> or pattern 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 else either leaves (return; break or continue in an iteration callback, §9; a trap such as unreachable "reason" or todo; 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) binds w to 80. A fallback of another type is the 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 error this 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 return is this pattern always matches; remove the else. A single-variant enum’s pattern always matches: for an enum Only whose one variant is One Int, Only.One(p) = only needs no else, and over a struct-shaped variant, Rec.Fields(r) = rec binds r to the anonymous struct of its fields.
  • A pattern that can fail requires one (Where patterns appear). On Ok(x) over a Result or Some(x) over a Maybe, the help points at ?: write x = ...?.
  • A ? inside the else exits the enclosing function or lambda, and return inside a lambda’s else exits the lambda.