Pattern Matching

Pattern matching destructures values and dispatches on their shape. It works on enum variants, literals, and wildcards, and can be used as both a statement and an inline expression.

match works on enums, literals, and wildcards.

enum Color { Red, Green, Blue }

fn describe(c: Color) -> str {
  match c {
    Red -> "warm"
    Green -> "natural"
    Blue -> "cool"
  }
}

Match can be used inline as an expression.

fn classify(n: int) -> str {
  match n {
    0 -> "zero"
    1 -> "one"
    _ -> "many"
  }
}

fn main() {
  println(describe(Red))
  println(describe(Blue))

  println(classify(0))
  println(classify(1))
  println(classify(99))
}
$ pyr run pattern-matching.pyr
warm
cool
zero
one
many