Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the `fun` and `function` keywords?

Tags:

f#

ocaml

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?

like image 659
Nick Heiner Avatar asked Oct 21 '09 23:10

Nick Heiner


People also ask

Is fun a keyword?

The fun keyword is used to define a lambda expression, that is, an anonymous function.

What does fun mean in coding?

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.

What does fun do in OCaml?

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.

How do you return a function in OCaml?

OCaml doesn't have a return keyword — the last expression in a function becomes the result of the function automatically.


1 Answers

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.

like image 176
Russ Cam Avatar answered Oct 17 '22 22:10

Russ Cam