Pergunta

I'm newbie with Scala, I'm having issue with currying and can't understand of how below code answer is 144. Hope you guys can help me here.

Thanks

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
Foi útil?

Solução

Here is nothing related with currying. You could rewrite your product method like this:

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

You could replace product(f, a, b) with f(a) * product(f, a+1, b) (in case a <= b) or with 1, you could also replace f(a) with a*a:

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

Outras dicas

First argument of this method is a function that maps integer to integer, ie. in given example, it squares the number passed to it.

Function 'product' then uses that function (passed as first parameter), and applies it to first argument ('a') and multiplies that result to recursive call to 'product' with same 'f', but with first argument incremented. As you can notice, parameter named 'b' doesn't play any computational role, other than limit to number of executions of function 'product'.

So, to resolve that call of 'product', we begin with 'a = 3, b = 4'. First, as 'a' is less than or equal to 'b', we go to else branch where we square (apply 'f') first parameter 'a' (which gives 9), and then multiply that with 'product(f)(4, 4)'. We also go to else branch here and there we square 4 (as value of 'a' in this execution of 'product') to get 16 and multiply it with 'product(f)(5, 4)'. Here, 'a' is greater than 'b', so we end 'product' with value 1.

As we propagate that back, we get 1 * 16 * 9 which, in turn equals 144.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top