Pattern Matching

Pattern matching provides powerful ways to destructure and match data.

Simple Patterns

kode
let value = 2

match (value) {
    1 => print("one"),
    2 => print("two"),
    3 => print("three"),
    _ => print("other")
}

Identifier Binding

kode
let x = 42

match (x) {
    0 => print("zero"),
    42 => print("the answer"),
    n => print("value: ${n}")
}

// Bind matched value to a name
fn describe(n: int) {
    match (n) {
        0 => print("zero"),
        1 => print("one"),
        n => print("many: ${n}")
    }
}

describe(0)    // zero
describe(5)    // many: 5

Destructuring Patterns

kode
let pair = (10, 20)

match (pair) {
    (a, b) => print("Pair: ${a}, ${b}")
}

let person = Person { name: "Alice", age: 30 }

match (person) {
    Person { name: n, age: a } => print("${n} is ${a} years old")
}

Enum Patterns

kode
enum Message {
    Click(x: int, y: int),
    Hover(x: int, y: int),
    Quit
}

let msg = Message.Click(10, 20)

match (msg) {
    Message.Click(x, y) => print("Clicked at ${x}, ${y}"),
    Message.Hover(x, y) => print("Hovering at ${x}, ${y}"),
    Message.Quit => print("Quit")
}

Guard Clauses

kode
let value = 15

match (value) {
    x if x < 10 => print("small"),
    x if x < 20 => print("medium"),
    x if x >= 20 => print("large"),
    _ => print("unknown")
}