F#:“有趣”吗?需要关键字吗?
我正在输入“fun”关键字,然后我记得在 C# 中不必这样做,
不是这样吗:
List.map (x -> x + 1) [1..10]
是否像这样富有表现力?:
List.map (fun x -> x + 1) [1..10]
这让我很好奇为什么“fun”关键字是必要的。有人可以澄清为什么语法上需要“fun”关键字吗?
I was typing the "fun" keyword and then I remembered you don't have to in C#
Wouldn't this:
List.map (x -> x + 1) [1..10]
Be just as expressive as this?:
List.map (fun x -> x + 1) [1..10]
This makes me curious as to why the "fun" keyword is necessary at all. Can someone clarify why the "fun" keyword is syntactically required?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果没有它,语言就会含糊不清。
x
是否在函数z ->; 上调用
还是忽略其参数并返回函数 yz -> y z ?y
y zThe language is ambiguous without it.
Does
x
cally
on the functionz -> y z
or does it ignore its argument and return the functiony z -> y z
?已经有很多不错的推测性答案...我将添加到其中:
F# 有一种与 OCaml 兼容的核心语言,并且 OCaml 使用“乐趣”。
Lots of decent speculative answers already... I'll add to the mix:
F# has a core language that's compatible with OCaml, and OCaml uses 'fun'.
我只是想分享一下,现在(从 f#8 开始)至少在非常特定的情况下可以完全避免 fun 和 lambda:当你的 lambda 只不过是一个原子表达式(即意味着,当 lambda 中的表达式在括号外没有任何空格时,例如将多个柯里化参数传递给函数时。)
例如:
现在可以写为:
请注意,在
exp3 的情况下
,我必须将数据参数传递到前面并通过管道传递函数,因此类型推断知道_
在该上下文中是int
。I just wanted to share that now it is possible (since f#8) to avoid the
fun
and lambdas altogether at least in a very specific situation: when your lambda is nothing more than an atomic expression (that means, when the expression in you lambda does not has any whitespace outside of a parentheses, like when you pass multiple curried arguments to a function.)For example:
Can now be written as:
Notice that, in the case of
exp3
, I had to pass the data argument to the front and pipe the function, so the type inference knows that_
is anint
in that context.我知道作为柯里化的一部分,(请参阅此 帖子)您可以替换:
与
没有乐趣关键词。
I know as part of currying, (see this post) you can replace:
with
without the fun keyword.