user701254
user701254

Reputation: 3953

Explain some code which uses recursion and currying

How is the method product used in this code ?

The result for this function is 3600

So product takes a function : f , f takes an Int parameter which returns an Int parameter.

But does (a: Int, b: Int) not indicate that a function which takes two Int parameters are returned ?

I'm confused as to what is is occuring in this line : f(a) * product(f)(a + 1, b)

Complete function :

 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 , 5)  

Upvotes: 0

Views: 953

Answers (1)

Jesper
Jesper

Reputation: 206926

In Scala, methods can have multiple parameter lists. In this example, the method product has two parameter lists: (f: Int => Int) and (a: Int, b: Int).

The first parameter list contains one parameter named f, which is of type Int => Int (a function that takes an Int and returns an Int).

The second parameter list contains two parameters named a and b which are both of type Int.

The expressions product(f)(a + 1, b) and product(x => x * x)(3 , 5) simply call the method with all three parameters.

The advantage of this is that you can "call" product with only the first parameter list. What you'll then get is a function that you can call by supplying the second parameter list. For example:

val fn = product(x => x * x)  // only the first parameter list is applied
fn(3, 5)                 // fn is a function which you can pass the second list

"Calling" product with only the first parameter list is called currying.

Upvotes: 4

Related Questions