F#: two ways of defining functions?
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 开发者_Go百科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?
They are equivalent (modulo the 'value restriction', which allows functions, but not values, to be generic, see e.g. here).
As Brian already answered, the two are equivalent. Returning fun
instead of declaring function using let
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:
let f1 x =
let rnd = new System.Random()
x + rnd.Next()
let f2 =
let rnd = new System.Random()
fun y -> y + rnd.Next()
Here, the function f1
creates new Random
instance every time it is executed, but f2
uses the same instance of rnd
all the time (so f2
is better way of writing this). But if you return fun
immediately, then the F# compiler optimizes the code and the two cases are the same.
精彩评论