views:

246

answers:

3

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?

+6  A: 

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.

the oCaml documentation on Functions

Russ Cam
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
Will update with more details now.
Russ Cam
My answer that referenced your's was also downvoted.
chollida
+2  A: 

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
couldn't you also do `let x y z = y + z`, with no `fun` or `function` at all?
Rosarch
@Rosarch, yes, of course. I think the question is implicitly about anonymous function definitions.
Chris Conway
@Rosarch, certainly:)
chollida
+4  A: 

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