match
match picks what to do by a value: it runs the block of the first case that has the value.
status: str = "banned"
match status {
"active" { print("user is active") }
"banned", "blocked" { print("no access") }
"pending" {
print("waiting for approval")
print("we'll let you know")
}
else { print("unknown status") }
}Output:
no accessIt says the same as a chain of ifs, if status == "active" { ... } else { if status == "banned" || status == "blocked" { ... } ... }, with the value written once.
Cases
- A case is one or more values, separated by commas, then its block. A short block fits on the line, a longer one goes on lines of its own, as with
if. - Only one case runs: the first with the value. Nothing falls through to the next one.
else, the last, runs if no case has the value. Without it, nothing runs then.
The values of the cases are fixed: literals, or locked values. The compiler checks them: each must be of the value’s type, and no value can be in two cases.
lock ADMIN: int = 0
fn role(id: int): str {
match id {
ADMIN { return "admin" }
1, 2, 3 { return "staff" }
else { return "user" }
}
}
print(role(0))
print(role(2))
print(role(42))Output:
admin
staff
userWhat can be matched
match works on int, byte and str values, and on trait values. For ints and bytes, a case can also be a range, both ends included:
fn grade(points: int): str {
match points {
(90..100) { return "A" }
(75..89) { return "B" }
(50..74) { return "C" }
else { return "F" }
}
}
print(grade(95))
print(grade(60))
print(grade(10))Output:
A
C
FA good use is the code of an error:
e: error = nil
try e {
n: int = convert("seven")
}
match e.code {
11 { print("that isn't a number") }
14 { print("network trouble") }
(100..999) { print("an error of our own: ${e.message}") }
else { throw e }
}Output:
that isn't a numberThe value after match is worked out once, before the cases are compared with it.
Matching obj types
On a trait value, the cases are obj types, and the value is that type in its case:
trait Pet {
fn name(): str
}
obj Dog: Pet {
tricks: int
fn name(): str => "dog"
}
obj Cat: Pet {
lives: int
fn name(): str => "cat"
}
pets: [Pet] = [Dog{tricks: 3}, Cat{lives: 9}]
pets.walk(p) {
match p {
Dog { print("a dog with ${p.tricks} tricks") }
Cat { print("a cat with ${p.lives} lives") }
}
}Output:
a dog with 3 tricks
a cat with 9 livesWithout else, every obj type that is the trait needs a case, so a new one can’t be forgotten.
Loops and functions
skip, stop and return in a case work on the loop or function the match is in, as they do in an if:
(1..10).walk(i) {
match i % 3 {
0 { skip }
1 { print(i) }
else {
if i > 6 {
stop
}
}
}
}Output:
1
4
7A function whose cases all return, with an else that does too, needs nothing after the match.