斯卡拉.按名称调用的高阶函数.是否有意义 [英] scala. higher order function calling by name. does it make sense
问题描述
只是想澄清一下.如果我们使用 higher-order function
(f. 接受另一个函数作为参数).指定 "=>"
符号来调用它 by-name
是否有意义.似乎 arg-function 正在调用 by-name
无论如何?
Just want to clarify. If we use higher-order function
(f. that accepts another function as argument). Does it make any sense specify "=>"
sign to call it by-name
. It seems arg-function is calling by-name
anyhow?
有一个例子:
// 1.
// the function that accepts arg-function with: two int params and returning String
// the function passing v1 & v2 as parameters to arg-function, invoking arg-function 2 times, connecting the result to one string
def takeFunction1(f: (Int, Int) => String, v1:Int, v2:Int ): String = {
f(v1, v2) + f(v1, v2)
}
// 2. same as #1 but calling arg-function by-name
def takeFunction2(f: => ((Int, Int) => String), v1:Int, v2:Int ): String = {
f(v1, v2) + f(v1, v2)
}
def aFun(v1:Int, v2:Int) : String = {
(v1 + v2).toString
}
// --
println( takeFunction1( aFun, 2, 2) )
println( takeFunction2( aFun, 2, 2) )
如果我想这样称呼它呢?:
And what if I want to call it like this ?:
println( takeFunction2( aFun(2,2)), ... ) // it tries to evaluate immediately when passing
推荐答案
不同之处在于,如果您将调用作为第一个参数传递给一个返回 (Int, Int) => 的函数.要使用的字符串
值,对生成器函数的调用仅使用传值计算一次,而在传值的情况下每次使用参数时都要计算一次.
The difference is that if you pass as the first argument a call to a function that returns the (Int, Int) => String
value to use, this call to the generator function is evaluated only once with pass-by-value, compared to being evaluated each time the argument is used in the case of pass-by-name.
相当人为的例子:
var bar = 0
def fnGen() = {
bar += 1
def myFun(v1:Int, v2:Int) = {
(v1 + v2).toString
}
myFun _
}
现在使用 fnGen 运行一些上述方法的调用:
Now run some calls of your methods above using fnGen:
scala> println( takeFunction1( fnGen(), 2, 2) )
44
scala> bar
res1: Int = 1
scala> println( takeFunction2( fnGen(), 2, 2) )
44
scala> bar
res3: Int = 3
如您所见,调用 takeFunction1
只会增加 bar
一次,而调用 takeFunction2
会增加 bar
两次.
As you can see, calling takeFunction1
increments bar
only once, while calling takeFunction2
increments bar
twice.
这篇关于斯卡拉.按名称调用的高阶函数.是否有意义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!