SML# Document Version 4.0.0
19 Expressions

19.18 Case expression case exp of match

This expresses general conditional branches on the value of exp. match is of the form

  pat1 => exp1
|
|
patn => expn

where each pati is a pattern containing data constructors and expi is the expression to be evaluated if pati is matched against the value of exp.

Each pattern pati 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 i such that 2lein, pati must not be redundant. In other words, the set of data covered by pati must not be a subset of the union of the sets of data covered by pat1, , pati-1.

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 expi.

This case expression is evaluated as follows. It tries to match the value of exp with each pattern from pat1 to patn in this order. For the first matched pattern pati, it binds variables in pati to their corresponding part of the value and evaluates expi to the result value. If no pattern matches with the value, it raises Match exception.