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.
Dynamic semantics.
To evaluate let p = e1 in e2:
Evaluate
e1to a valuev1.Match
v1against patternp. If it doesn't match, raise the exceptionMatch_failure. Otherwise, if it does match, it produces a set of bindings.Substitute those bindings in
e2, yielding a new expressione2'.Evaluate
e2'to a valuev2.The result of evaluating the let expression is
v2.
Static semantics.
If all the following hold:
e1:t1- the pattern variables in
parex1..xn e2:t2under the assumption that for alliin1..nit holds thatxi:ti,
then
(let p = e1 in e2) : t2.
Let definitions.
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.