如何在 Scala 中柯里化函数
我试图在 List.foreach 中调用 2 个参数函数,第一个参数固定用于循环。事实上,我想将两个参数的函数柯里化为一个参数的函数,该函数返回一个参数的函数(如 List.foldLeft 所做的那样)
这不起作用:
private def mathFunc1(a: Double, b: Double) =
println(a + b)
def eval(v: Double) = {
List(1.0, 2.0, 3.0).foreach(mathFunc1(2.1))
}
这有效:
private def mathFunc2(a: Double)(b: Double) =
println(a + b)
def eval(v: Double) = {
List(1.0, 2.0, 3.0).foreach(mathFunc2(2.1))
}
但我不想更改mathFunc1,所以我想做类似的事情:
private def mathFunc1(a: Double, b: Double) =
println(a + b)
def eval(v: Double) = {
List(1.0, 2.0, 3.0).foreach(CONVERT_TWO_PARAMS_TO_ONE_ONE(mathFunc1)(2.1))
}
I'm trying to call a 2 parameters function in List.foreach, with the first parameter fixed for a loop. In fact I want to curry a function of two parameters into a function of one parameter which returns a function of one parameter (as List.foldLeft do)
This does not work:
private def mathFunc1(a: Double, b: Double) =
println(a + b)
def eval(v: Double) = {
List(1.0, 2.0, 3.0).foreach(mathFunc1(2.1))
}
This works:
private def mathFunc2(a: Double)(b: Double) =
println(a + b)
def eval(v: Double) = {
List(1.0, 2.0, 3.0).foreach(mathFunc2(2.1))
}
But I don't want to change the signature of mathFunc1, so I want to do something like:
private def mathFunc1(a: Double, b: Double) =
println(a + b)
def eval(v: Double) = {
List(1.0, 2.0, 3.0).foreach(CONVERT_TWO_PARAMS_TO_ONE_ONE(mathFunc1)(2.1))
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
下划线,Scala 通配符!
作为一个小小的好奇心,这也将起作用:
或者甚至:
Underline, the Scala wildcard!
As a minor curiosity, this will also work:
Or even: