44

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?

John Källén
  • 7,551
  • 31
  • 64
Nick Heiner
  • 119,074
  • 188
  • 476
  • 699
  • 2
    Removed the 'fun' tag, since it has an established meaning other than your intent here. I think the question will be better off without it, since some people filter it out using the ignore list. – Bill the Lizard Oct 22 '09 at 17:50

4 Answers4

50

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.

Rok Strniša
  • 6,781
  • 6
  • 41
  • 53
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
  • 5
    I didn't downvote, but, describing 'fun' as preferred because it's more compact isn't the whole story, it isn't even a description of how to use it, and in no way are you comparing the two keywords! function is the same as saying, (fun x -> match x with ...), how is that more compact if you plan to pattern match? – nlucaroni Oct 22 '09 at 15:00
  • 7
    `fun` also allows the use of pattern matching, but with only one alternative, like `let` – newacct Nov 27 '11 at 07:16
24

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.)

Brian
  • 117,631
  • 17
  • 236
  • 300
8

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

chollida
  • 7,834
  • 11
  • 55
  • 85
1
fun x1 ... xn -> e

is an abbreviation for

function x1 -> ... -> function xn -> e
Matthew Hannigan
  • 1,487
  • 1
  • 14
  • 17