19.18 Case expression case exp of match
This expresses general conditional branches on the value of exp. match is of the form
pat => exp
|
| pat => exp
where each pat is a pattern containing data constructors and exp is the expression to be evaluated if pat is matched against the value of exp.
Each pattern pat is a data pattern consisting of constructors and variables, as described in Chapter 20. This set of patterns must satisfy the following restrictions:
-
•
All variables occurring in a pattern must be distinct.
-
•
Every pattern must have the same type as the type of exp.
-
•
For any such that , pat must not be redundant. In other words, the set of data covered by pat must not be a subset of the union of the sets of data covered by pat, , pat.
For example, the following violates the third rule.
# fn x => case x of (X, 1, 2) => 1 | (1, X, 2) => 2 | (1, 1, 2) => 3;
(interactive):6.8-6.65 Error: match redundant and nonexhaustive
(X, 1, 2) => ...
(1, X, 2) => ...
--> (1, 1, 2) => ...
Under these restrictions, this entire expression has the same type as each expression exp.
This case expression is evaluated as follows. It tries to match the value of exp with each pattern from pat to pat in this order. For the first matched pattern pat, it binds variables in pat to their corresponding part of the value and evaluates exp to the result value. If no pattern matches with the value, it raises Match exception.