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)
In Scala, methods can have multiple parameter lists. In this example, the method
producthas two parameter lists:(f: Int => Int)and(a: Int, b: Int).The first parameter list contains one parameter named
f, which is of typeInt => Int(a function that takes anIntand returns anInt).The second parameter list contains two parameters named
aandbwhich are both of typeInt.The expressions
product(f)(a + 1, b)andproduct(x => x * x)(3 , 5)simply call the method with all three parameters.The advantage of this is that you can “call”
productwith 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:“Calling”
productwith only the first parameter list is called currying.