Matching with switch
Grammar: switch-stmt, arm, position
switch matches one or more values, its subjects, against a list of arms, and runs the first arm that matches them all. Each subject is evaluated once, left to right, before any arm is tried, so a call is as good a subject as a variable.
An arm has one position per subject, separated by commas, and a position is:
- a pattern, exactly as it would be after
is:Shape.Circle(r),Result.Ok([first, ...rest]),"/users/{id}"; - a literal the value has to equal:
0,-1,#Ready,true; _, which takes any value.
An arm is the if its positions spell, so what it binds is in scope in its body and nowhere else, and it binds a name once across all its positions. Nothing falls through: only the first arm that matches runs, and break and continue act on the loop around the switch.
Two things are compile errors. A combination of values no arm takes is one, and the message names it — Shape.Circle(_), Fill.Empty — so a switch is always exhaustive: coverage works as on the previous slide, over every subject at once, and a number, an atom or a string needs a _. An arm that can never run, because the arms above it already take everything it would, is the other. So a switch whose every arm returns ends a function, with nothing after it.
type Shape {
Circle { radius: Int }
Point
}
type Fill {
Solid { color: Str }
Empty
}
// Every shape with every fill has an arm, so the switch ends the function.
func describe(shape: Shape, fill: Fill): Str {
switch shape, fill {
Shape.Circle(r), Fill.Solid(color) { return "a {color} circle of {r}" }
Shape.Circle(r), Fill.Empty { return "an empty circle of {r}" }
Shape.Point, _ { return "a point" }
}
}
proc main(): void {
echo describe(Shape.Circle(2), Fill.Solid("red")) // a red circle of 2
echo describe(Shape.Circle(5), Fill.Empty()) // an empty circle of 5
echo describe(Shape.Point(), Fill.Solid("blue")) // a point
}// Without the last arm this is a compile error, since no finite set of
// numbers covers an Int; and an arm under that one could never run, which
// is a compile error too.
func size(n: Int, loud: Bool): Str {
switch n, loud {
0, _ { return "none" }
1, true { return "ONE" }
1, false { return "one" }
_, _ { return "many" }
}
}
proc main(): void {
echo size(0, true) // none
echo size(1, true) // ONE
echo size(7, false) // many
}proc main(): void {
names := ["ada", "bob"]
for each wanted in ["bob", "eve"] {
// The call is made once, before any arm is tried.
switch indexOf(names, wanted) {
Result.Ok(i) { echo "{wanted} is at {i}" }
Result.Error(_) { echo "no {wanted}" }
}
}
}