gpt4 book ai didi

Scala 部分应用不清楚

转载 作者:行者123 更新时间:2023-12-04 17:34:52 25 4
gpt4 key购买 nike

我不是很清楚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))

输出将是:
calculate
complexVal calculated
result(3): 13
complexVal calculated
result(1): 11

所以 complexVal被计算了 2 次,如果我只想计算一次怎么办?

对于谁拥有 javascript 知识,例如:
function myOperation(x) {
var complexVal = complexCalc(x)
return function(y){
complexVal + y
}
}

编辑 :
那么我之前写的和这个有什么区别:
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)

最佳答案

您可以从 myOperation 显式返回一个函数:

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

关于Scala 部分应用不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23872818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com