Scala局部应用不清楚

ras*_*cio 5 scala partial-application

我不太清楚在Scala中部分应用函数...我会做一个例子:

def myOperation(x: Int)(y: Int): Int = {
    val complexVal = complexCalc(x)
    println("complexVal calculated")
    complexVal + y
}
def complexCalc(x: Int): Int = x * 2

val partial = myOperation(5)_

println("calculate")
println("result(3): " + partial(3))
println("result(1): " + partial(1))
Run Code Online (Sandbox Code Playgroud)

这个输出将是:

calculate
complexVal calculated
result(3): 13
complexVal calculated
result(1): 11
Run Code Online (Sandbox Code Playgroud)

所以complexVal计算了2次,如果我只计算一次呢?

对于谁有javascript知识的东西:

function myOperation(x) {
     var complexVal = complexCalc(x)
     return function(y){
         complexVal + y
     }
}
Run Code Online (Sandbox Code Playgroud)

编辑:
那么我之前写的和之间的区别是什么:

def myOperation2(x: Int, y: Int): Int = {
    val complexVal = complexCalculation(x)
    println("complexVal calculated")
    complexVal + y
}

val partial = myOperation(5)_
val partial2 = myOperation2(5, _: Int)
Run Code Online (Sandbox Code Playgroud)

Lee*_*Lee 4

您可以显式地从以下位置返回一个函数myOperation

def myOperation(x: Int): Int => Int = {
    val complexVal = complexCalc(x)
    println("complexVal calculated")
    (y: Int) => complexVal + y
}
Run Code Online (Sandbox Code Playgroud)

  • 人们经常将多个参数列表函数误认为是柯里化,但事实并非如此。真正的柯里化,就是这里所做的,实际上执行一个返回另一个函数的函数。多参数列表函数绝不是实际柯里化函数的“简写”。 (3认同)