Sometimes I see code like
let (alt : recognizer -> recognizer -> recognizer) =
fun a b p -> union (a p) (b p)
Or like:
let hd = function
Cons(x,xf) -> x
| Nil -> raise Empty
What is the difference between fun
and function
?
Sometimes I see code like
let (alt : recognizer -> recognizer -> recognizer) =
fun a b p -> union (a p) (b p)
Or like:
let hd = function
Cons(x,xf) -> x
| Nil -> raise Empty
What is the difference between fun
and function
?
If it's the same as F# (which I imagine it would be considering F# is based on oCaml),
function
allows you to use pattern matching, but consequently it can be passed only one argument.
fun
is generally preferred as it's more compact.
EDIT:
I'm not sure why this answer was downvoted, the above is absolutely correct.
Russ Cam is correct in his answer.
Here is a posting on the OCaml list talking about it
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
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.)