Pelago
Pattern matching

Pattern matching

switch and is: choosing by value and by shape, one page for each kind of pattern, guards, exhaustiveness and in-place matching.

Pelago has a single construct for branching on what a value is: switch. It handles numbers, text, enums, structs, tuples, lists, options and results. It is an expression, so each case produces a value, and the compiler checks that every possible shape is covered.

fn classify(n: int) -> string {
    switch n {
        case 0: "zero"
        case 1, 2, 3: "small"
        case 4..10: "medium"
        default: "large"
    }
}

fn main() {
    for n of [0, 2, 5, 50] { print(classify(n)) }
}
zero
small
medium
large

The shape of a switch

switch value {
    case pattern: result
    case pattern if condition: result
    default: result
}
  • Cases are tried in order; the first match wins.
  • Each case is one expression or a block; the whole switch has the type of its cases.
  • A switch used as a statement can have cases that just do something and produce no value.
  • If the value has a fixed set of shapes (an enum, an option, a result, a bool) the compiler requires every one to be covered, or a default.

Pages

PagePatterns
Values and rangesLiterals, several values per case, ranges, text, characters, bool.
EnumsCases, their fields, nested patterns.
Structs and tuplesField patterns, .., tuple positions.
Lists[], [x], [first, ..., last], [h, ...t], literals inside.
Options and resultssome, none, ok, err.
Guards, default and exhaustivenessif conditions, binding names, default, the missing-case error.
isA pattern as a yes or no test, in if, while, guard and list builders.
Matching in placeswitch x! to change what you matched.

Where patterns appear

Besides switch and is, patterns are used to unpack values in declarations: const (a, b, c) = t. See Tuples.

On this page