F#:定义函数的两种方法?
这两个是等价的:
let f(x) =
10
let g = fun(x) ->
10
我认为?他们似乎做同样的事情,但是在某些情况下两者的行为会有所不同吗?我发现第二个版本很有用(即使更冗长),因为您可以使用 <|
和 <<
运算符来实现 python 风格的装饰器模式;有没有什么情况我必须使用第一个版本?
此外,我完全理解第二个是如何工作的(右边的东西只是一个函数表达式,我将其转储到 g 中)但是第一个怎么样?是否有一些编译器技巧或特殊情况将该语法从简单的赋值语句转换为函数定义?
These two are equivalent:
let f(x) =
10
let g = fun(x) ->
10
I think? They seem to do the same thing, but are there any cases where the behavior of the two would vary? I find the second version useful (even if more verbose) because you can use the <|
and <<
operators to implement python-style decorator patterns; is there any case where I have to use the first version?
Furthermore, I fully understand how the second one works (the stuff on the right is just a function expression, which I dump into g) but how about the first one? Is there some compiler trick or special case that converts that syntax from a simple assignment statement into a function definition?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它们是等价的(以“值限制”为模,允许函数而不是值是通用的,请参见例如
They are equivalent (modulo the 'value restriction', which allows functions, but not values, to be generic, see e.g. here).
正如布莱恩已经回答的那样,两者是等价的。如果您想在返回函数之前执行某些操作(即一些初始化),则返回
fun
而不是使用let
声明函数会有所不同。例如,如果您想创建添加随机数的函数,您可以编写:
这里,函数
f1
每次执行时都会创建新的Random
实例,但是f2
始终使用相同的rnd
实例(因此f2
是更好的编写方式)。但如果立即返回fun
,那么 F# 编译器会优化代码,两种情况是相同的。As Brian already answered, the two are equivalent. Returning
fun
instead of declaring function usinglet
makes difference if you want to do something (i.e. some initialization) before returning the function.For example, if you wanted to create function that adds random number, you could write:
Here, the function
f1
creates newRandom
instance every time it is executed, butf2
uses the same instance ofrnd
all the time (sof2
is better way of writing this). But if you returnfun
immediately, then the F# compiler optimizes the code and the two cases are the same.