Scala课程"Currying"

Mon*_*ter 2 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
Run Code Online (Sandbox Code Playgroud)

sen*_*nia 5

这与此无关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
Run Code Online (Sandbox Code Playgroud)

您可以替换product(f, a, b)f(a) * product(f, a+1, b)(如果<= b)或with 1,您也可以替换f(a)a*a:

product(f, 3, 4) ==
9 * product(f, 4, 4) ==
9 * ( 16 * product(f, 5, 4) ) ==
9 * ( 16 * 1 ) ==
144
Run Code Online (Sandbox Code Playgroud)