What is the difference between the `fun` and `function` keywords?
The semantics for this is the same as in F# (probably because F# is based on OCaml):
function
allows the use of pattern matching (i.e.|
), but consequently it can be passed only one argument.function p_1 -> exp_1 | … | p_n -> exp_n
is equivalent to
fun exp -> match exp with p_1 -> exp_1 | … | p_n -> exp_n
fun
does not allow pattern matching, but can be passed multiple arguments, e.g.fun x y -> x + y
When either of the two forms can be used, fun
is generally preferred due to its compactness.
See also OCaml documentation on Functions.
The way I think about it
function patterns
is shorthand for
(fun x -> match x with patterns)
where 'patterns' is e.g.
| Some(x) -> yadda | None -> blah
(And
fun args -> expr
is how you define a lambda.)
Russ Cam is correct in his answer.
Here is a posting on the OCaml list talking about it
http://caml.inria.fr/pub/ml-archives/ocaml-beginners/2003/11/b8036b7a0c1d082111d7a83c8f6dbfbb.en.html
function
only allows for one argument but allows for pattern matching, while fun
is the more general and flexible way to define a function.
I generally use fun unless there is a good reason to use function.
You can see this in the code you posted where the fun
declaration takes 3 arguments and the function
declaration does pattern matching on it's input