开发者

When to use 'function' instead of 'fun'? [duplicate]

This question already has answers here: 开发者_JAVA技巧 Closed 12 years ago.

Possible Duplicate:

F# explicit match vs function syntax

Hello,

I am learning F# and am confused by 'fun' and 'function' keywords. My understanding is that these are sort of the same thing.

// Use 'fun'
let testFunction1 = fun argument -> match argument with
                                    | Some(x) -> x
                                    | None    -> 0

// Use 'function'
let testFunction2 = function
                    | Some(x) -> x
                    | None    -> 0

Is 'function' just shorthand for "fun x -> match x with"? Is there any runtime / optimization difference between the two? Why would I prefer to use one over the other?

As it stands, 'function' just seems to make code harder to read. Am I missing something?


function only allows for one argument but allows for pattern matching, while fun is the more general and flexible way to define a function. Take a look here: http://caml.inria.fr/pub/docs/manual-ocaml/expr.html


It is simply syntactic sugar. Just like in C# c => c = 'A' is syntax sugar for delegate (char c) { return c = 'A'; }. It all comes down to personal preference really.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜