Pattern Matching with Let
The syntax we've been using so far for let expressions is, in fact, a special case of the full syntax that OCaml permits. That syntax is:
let p = e1 in e2
That is, the left-hand side of the binding may in fact be a pattern, not just an identifier. Of course, variable identifiers are on our list of valid patterns, so that's why the syntax we've studied so far is just a special case.
Given this syntax, we revisit the semantics of let expressions.
let p = e1 in e2:
e1to a value
p. If it doesn't match, raise the exception
Match_failure. Otherwise, if it does match, it produces a set of bindings.
Substitute those bindings in
e2, yielding a new expression
e2'to a value
The result of evaluating the let expression is
If all the following hold:
- the pattern variables in
e2:t2under the assumption that for all
1..nit holds that
(let p = e1 in e2) : t2.
As before, let definitions can be understood as let expression whose body has not yet been given. So their syntax can be generalized to
let p = e
and their semantics follow from the semantics of let expressions, as before.