Scala 类(class) "Currying"

标签 scala currying

我是 Scala 新手,我在柯里化(Currying)方面遇到问题,无法理解下面的代码答案是 144。希望你们能在这里帮助我。

谢谢

def product (f: Int => Int)(a: Int, b: Int) : Int =
   if(a>b) 1
   else f(a) * product(f)(a + 1, b)

product(x => x * x)(3, 4) //answer = 144

最佳答案

这里与柯里化(Currying)无关。您可以像这样重写您的 product 方法:

def product(f: Int => Int, a: Int, b: Int) : Int =
   if(a>b) 1
   else f(a) * product(f, a + 1, b)

val f = (x: Int) => x*x

product(f, 3, 4) // still 144

您可以将 product(f, a, b) 替换为 f(a) * Product(f, a+1, b) (如果 a <= b) 或者使用 1,您也可以将 f(a) 替换为 a*a:

product(f, 3, 4) ==
9 * product(f, 4, 4) ==
9 * ( 16 * product(f, 5, 4) ) ==
9 * ( 16 * 1 ) ==
144

关于Scala 类(class) "Currying",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21235737/

相关文章:

参数数量可变的 Python 柯里化(Currying)函数

scala - 在 Scala 中调用柯里化(Currying)函数?

java - 我可以在运行时更改 Spark 的执行程序内存吗?

java - 如何强制 Scala 中指令的执行顺序

scala - 如何在运行期间在Spark中设置执行程序内存

regex - 在Scala中的两个字符串之间提取字符串

c++ - 推导重载函数的类型 - currying

ruby - 如何在 ruby​​ 中实现 curry(部分函数)

scala - 柯里化(Currying)第一个参数组

scala - 用于 Ocaml 和其他语言的基于 Actor 的分布式并发库