Reputation: 2160
I am learning Scala and I don't quite understand:
why the code sum1 can't be rewritten by sum2?
why in sum1, a and b automatically know (Int,Int) correspond to a and b?
Thanks in advance.
def sum1 (f: Int => Int) : (Int, Int) => Int = {
def sumF(a:Int, b:Int) : Int = {
if (a > b) 0
else f(a) + sumF(a + 1, b)
}
sumF
}
def sum2 (f: Int => Int, Int, Int) : Int = {
def sumF(a:Int, b:Int) : Int = {
if (a > b) 0
else f(a) + sumF(a + 1, b)
}
sumF
}
Upvotes: 1
Views: 51
Reputation: 1240
It's because sum1
and sum2
have different interfaces: sum1
is (Int => Int) => ((Int, Int) => Int)
and sum2
is (Int => Int, Int, Int) => Int
. I.e. sum1
returns function that accepts two integers and returns an integer. But sum2
returns just an integer value, not a function.
Your sumF
function equal to a lambda function
val sumF: (Int, Int) => Int = (a: Int, b: Int) => {
if (a > b)
0
else
f(a) + sumF(a + 1, b)
}
You can see it if you try to save sumF
into value (it would look like val tmp: (Int, Int) => Int = sumF
)
Upvotes: 3