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:
x1..xnbe the pattern variables appearing in
p. If by assuming that
x2:t2and ... and
xn:tn, we can conclude that
fun p -> e : t -> u.
The type checking rule for application is unchanged.
The evaluation rule for anonymous functions is unchanged.
e0to an anonymous function
fun p -> e, and evaluate
p. If it doesn't match, raise the exception
Match_failure. Otherwise, if it does match, it produces a set \(b\) of bindings.
Substitute those bindings \(b\) in
e, yielding a new expression
e'to a value
v, which is the result of evaluating