0

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

Thanks.

Tim
  • 1
  • 141
  • 372
  • 590

1 Answers1

2

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.

Andreas Rossberg
  • 34,518
  • 3
  • 61
  • 72
  • Thanks. Are patterns not expressions? What are they? I thought only expressions can have types. – Tim Apr 30 '20 at 09:03
  • 1
    Patterns are patterns. They are a different syntactic category from expressions (whose structure mostly mirrors a subset of expressions). Types can be assigned to many phrases. In ML, for example, modules have types as well, though they are usually called signatures and are different from the types of values. – Andreas Rossberg Apr 30 '20 at 11:07