steve steve - 1 year ago 124
Scala Question

Curry function in scala

object answer {
def product(f:Int=>Int)(a:Int,b:Int):Int =
if (a>b) 1
else f(a) * product(f)(a+1,b)
def fact(n:Int) = product(x=>x)(1,n)

I can answer the result of this execution it like this:

// 3*3* product(f)(4,4)
// 3*3 * (4*4) * product(f)(5,4)
// 3*3 * 4*4 * 1
// 3*3 * 4*4
// 144

However I dont I understand this block of code
anyone can explain me about that line?

Answer Source

The block of code product(f)(a+1,b) is a call of method product with arguments: f, a+1 and b.

More details:

product is a recursive higher-order function with multiple parameter lists.

  • It is recursive since there is a call to itself in its body.
  • It is higher-order since it takes a function as an argument (see higher-order functions).
  • It has two parameter lists (see currying):
    • the first one consist of a single parameter: a function f:Int=>Int;
    • the second contains two parameters: a: Int and b: Int.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download