“fun”和“function”关键字有什么区别?
代码
let (alt : recognizer -> recognizer -> recognizer) =
fun a b p -> union (a p) (b p)
有时我会看到类似或类似的
let hd = function
Cons(x,xf) -> x
| Nil -> raise Empty
: fun
和 function
之间有什么区别?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
其语义与 F# 中的语义相同(可能是因为 F# 基于 OCaml):
function
允许使用模式匹配(即|
),但是因此它只能传递一个参数。相当于
fun
不允许模式匹配,但可以传递多个参数,例如当可以使用两种形式中的任何一种时,
fun
通常是由于其紧凑性而受到青睐。另请参阅有关函数的 OCaml 文档。
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.is equivalent to
fun
does not allow pattern matching, but can be passed multiple arguments, e.g.When either of the two forms can be used,
fun
is generally preferred due to its compactness.See also OCaml documentation on Functions.
我的想法
是“模式”的简写
,例如
(并且
是定义 lambda 的方式。)
The way I think about it
is shorthand for
where 'patterns' is e.g.
(And
is how you define a lambda.)
Russ Cam 的回答是正确的。
这是 OCaml 列表上的一个帖子,讨论它
http://caml.inria.fr/pub/ml-archives/ocaml-beginners/2003/11/b8036b7a0c1d082111d7a83c8f6dbfbb.en.html
function
只允许一个参数,但允许对于模式匹配,而fun
是定义函数的更通用和灵活的方式。我通常使用 fun ,除非有充分的理由使用 function 。
您可以在您发布的代码中看到这一点,其中
fun
声明采用 3 个参数,而function
声明对其输入进行模式匹配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, whilefun
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 thefunction
declaration does pattern matching on it's input是一个缩写
is an abbreviation for