functional-programmingpattern-matchingprogramming-languagessmlml

Should the patterns in a SML match expression have the same type?


In Ullman's SML book:

A match expression consists of one or more rules, which are pairs of the form

<pattern> => <expression>

The rules are separated by vertical bars, so the form of a match is:

<pattern 1> => <expression 1> |
<pattern 2> => <expression 2> |
<pattern n> => <expression n>

Each of the expressions following the =>'s must be of the same type, since any one of them could become the value of the match.

Are the patterns in a match expression expressions (so they have types)?

Should the patterns in a match expression also have the same type?

In particular, when a match expression is used for defining a function, such as

val rec f = fn P1 => E1 | P2 => E2 | ... | Pn => En;

should the patterns in the match expression also have the same type? (I guess yes, because the parameters of a function have types, and we can't give arguments of different types to the same parameter.)


Solution

  • Yes, just like expressions, patterns have types. And the types of the different patterns in a match must be the same.

    For case, the pattern type must also be the same as the type of the scrutinee expression. For functions, the pattern type is the function's parameter type.