Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

f# - What is the difference between the `fun` and `function` keywords?

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?

question from:https://stackoverflow.com/questions/1604270/what-is-the-difference-between-the-fun-and-function-keywords

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...