In the previous section, we saw how to use the switch expression. But that barely scratched the surface of what switch can do. Switch expressions match against arbitrary patterns and evaluate the branch that corresponds to the first matching pattern.
Here's a slightly more formal syntax for a switch expression:
switch (expr) {
| pat1 => res1
| pat2 => res2
...
| patN => resN
}
This entire syntactic form evaluates to a single value. Each subsection of the expression that starts with a bar character (|) is called a branch.
The steps for evaluating the expression are as follows:
- Evaluate expr.
- Match the value of expr against pat1; if it matches, evaluate the entire expression to res1 and ignore all the other branches.
- Otherwise, continue matching the value against each pattern in turn, and evaluate to the first result that corresponds to the matching...