6.14 Matching
expression | ||||||||
| ||||||||
| ||||||||
expression | ||||||||
| ||||||||
| ||||||||
expression | ||||||||
|
Typically, a bind imposes requires on a value and binds some number of identifiers as a result of a successful match. For example, a literal number works as a bind pattern, but it binds zero identifiers. An identifier as a bind pattern matches any value and binds the identifier the the matching value. A list form is a bind pattern with subpatterns as its elements, and it matches a list with the right number of elements that match match the corresponding pattern. A when or unless can impose a side condition on a match. The set of bind forms is extensible, so it cannot be completely enumerated here.
If no target_expr produces a true value and there is no ~else clause, a run-time exception is thrown. In that case, when all of the bind forms are syntax-object patterns, the generated exception’s message may be specialized to report the expected pattern, instead of just reporting that no cases matched.
If an initial segment of bind patterns are literals or combinations of literals with ||, then the match is implemented as a case dispatch, and a match is found with logarithmic rather than linear time complexity in the number of literals. The remaining patterns are handled as usual.
| 3: "three"
| ~else: "not three"
"three"
| [x, y]: x+y
10
> match 'go ~slow'
| 'go ~fast': "ok"
match: expected the keyword ~fast
| n when n > 4: "ok"
match: no matching case
#true
#true
binding operator |
| 0: "zero"
| _: "nonzero"
"nonzero"
binding operator | |||||||||
| |||||||||
binding operator | |||||||||
| |||||||||
| |||||||||
|
The where form should generally be used with parentheses around it, since parsing is otherwise likely to interact badly with the enclosing context, such as conflicting interpretations of a = by where and def.
> f([1, 2, 3])
'1 2 3 = 6'
> f([0, 2, 3])
"something else"
def: value does not satisfy annotation
value: ["oops"]
position: 1st
annotation: matching(List(_)) where ....