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
?
The fun keyword is used to define a lambda expression, that is, an anonymous function.
void fun() is a function that does not return a value (essentially nothing). :: is a scope resolution operator. For example, cout and cin are defined in the std namespace. To qualify their names without using the using declaration we have to qualify them with std::cout and std::cin.
Similarly, OCaml functions do not have to have names; they may be anonymous. For example, here is an anonymous function that increments its input: fun x -> x + 1 . Here, fun is a keyword indicating an anonymous function, x is the argument, and -> separates the argument from the body.
OCaml doesn't have a return keyword — the last expression in a function becomes the result of the function automatically.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With