我是 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/