Pattern Matching with Functions
The syntax we've been using so far for functions is also a special case of the full syntax that OCaml permits. That syntax is:
let f p1 ... pn = e1 in e2 (* function as part of let expression *)
let f p1 ... pn = e (* function definition at toplevel *)
fun p1 ... pn -> e (* anonymous function *)
The truly primitive syntactic form we need to care about is
fun p -> e. Let's revisit the semantics of anonymous functions
and their application with that form; the changes to the other forms
follow from those below:
Static semantics.
Let
x1..xnbe the pattern variables appearing inp. If by assuming thatx1:t1andx2:t2and ... andxn:tn, we can conclude thatp:tande:u, thenfun p -> e : t -> u.The type checking rule for application is unchanged.
Dynamic semantics.
The evaluation rule for anonymous functions is unchanged.
To evaluate
e0 e1:Evaluate
e0to an anonymous functionfun p -> e, and evaluatee1to 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
e, yielding a new expressione'.Evaluate
e'to a valuev, which is the result of evaluatinge0 e1.