Pattern matching
match compares a value with patterns, from top to bottom, and runs the branch of the first that fits. It's an expression: it gives the value of that branch.
fn describe(n: Int): String = match n {
0 -> "zero"
1 -> "one"
_ -> "many"
}
println(describe(1))
println(describe(5))one many
_ matches anything. Each branch is an expression, a single statement, or a block in braces:
let command = "stop"
match command {
"go" -> println("going")
"stop" -> {
println("stopping")
println("stopped")
}
_ -> println("unknown command")
}stopping stopped
#Every case is covered
A match must handle every possible value: every case of an enum, both true and false, null for a nullable value, or have a _ branch. A missing case is an error before the program runs:
enum Light { Red, Yellow, Green }
fn next(light: Light): Light = match light {
Red -> Green
Green -> Yellow
}Type error: 'match' doesn't cover every case. Missing: Yellow. Add it or a '_ ->' branch --> main.zyn:3:32 | 3 | fn next(light: Light): Light = match light { | ^
#Patterns
| Pattern | Matches |
|---|---|
42, "text", 'c', true, null, -1 | That exact value |
0..<13, 'a'..'z' | A value in the range |
_ | Anything |
n (a lowercase name) | Anything, and gives it the name n |
Circle(r) | That enum case, naming its fields |
Circle | That enum case, whatever its fields |
User(name, _) | A data value, naming its fields |
pattern if condition | The pattern, when the condition is also true |
Patterns nest: Login(User(name, _)) matches a Login whose user it names name.
#Ranges
fn ageGroup(age: Int): String = match age {
0..<13 -> "child"
13..<20 -> "teenager"
_ -> "adult"
}
fn kind(c: Char): String = match c {
'a'..'z' -> "small letter"
'A'..'Z' -> "capital"
'0'..'9' -> "digit"
_ -> "other"
}
println(ageGroup(15))
println(kind('Q'))teenager capital
#Enum cases and their fields
enum Event {
Click(x: Int, y: Int)
Key(char: Char)
Quit
}
fn handle(e: Event): String = match e {
Click(x, y) -> "click at {x}, {y}"
Key(c) -> "key {c}"
Quit -> "bye"
}
println(handle(Click(3, 4)))
println(handle(Key('z')))
println(handle(Quit))click at 3, 4 key z bye
#Data types, nested
data User(name: String, admin: Bool)
enum Request {
Login(user: User)
Logout
}
fn greet(r: Request): String = match r {
Login(User(name, true)) -> "Welcome back, admin {name}"
Login(User(name, _)) -> "Hello, {name}"
Logout -> "Goodbye"
}
println(greet(Login(User("Ada", true))))
println(greet(Login(User("Bob", false))))Welcome back, admin Ada Hello, Bob
#Guards
if after a pattern adds a condition. A branch with a guard doesn't count toward covering every case:
enum Shape {
Circle(radius: Float)
Rect(width: Float, height: Float)
}
fn describe(s: Shape): String = match s {
Rect(w, h) if w == h -> "a square"
Rect(_, _) -> "a rectangle"
Circle(r) if r > 10.0 -> "a big circle"
Circle(_) -> "a circle"
}
println(describe(Rect(2.0, 2.0)))
println(describe(Circle(20.0)))a square a big circle
#Match without a value
match without a value checks conditions, top to bottom, and is a neat replacement for long if/else if chains. Branches can also be on one line, separated by commas:
fn fizzBuzz(n: Int): String = match {
n % 15 == 0 -> "FizzBuzz"
n % 3 == 0 -> "Fizz"
n % 5 == 0 -> "Buzz"
_ -> "{n}"
}
println((1..15).map { fizzBuzz(it) }.joinToString(" "))
let x = -4
println(match { x > 0 -> "positive", x < 0 -> "negative", _ -> "zero" })1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz negative
#Classes
Objects of classes aren't patterns; check their type with is in a match without a value:
open class Animal(let name: String)
class Dog(name: String) : Animal(name)
class Cat(name: String) : Animal(name)
fn sound(a: Animal): String = match {
a is Dog -> "{a.name} says woof"
a is Cat -> "{a.name} says meow"
_ -> "..."
}
println(sound(Dog("Rex")))
println(sound(Cat("Tom")))Rex says woof Tom says meow