Hello, and welcome to the community.
First of all, for futures questions, it would be better to put code (as text) rather than images.
Second, I believe that the core concept you are missing here are functions.
Scala, has functions as first class citizens. That means that functions are values, you can assign them to values, pass them as arguments, and return them and have methods associated to them.
So let’s try to understand what is happening.
def sum(f: Int => Int): (Int, Int) => Int
So we have a method sum
which receives a function from an Int
to an Int
, and returns another function from two Ints
into an Int
.
Now, as you can see, what the sum
method does is creates another method sumF
and return it (the compiler can implicitly transform methods into functions when the last is required).
So let’s see the body of sumF
def sumF(a: Int, b: Int): Int =
if (a > b) 0 else f(a) + sumF(a + 1, b)
So we got a method that receives two Ints
and returns an Int
.
And the body is quite simple, if a
is greater than b
then returns zero, otherwise return the sum of f(a)
with sumF(a + 1, b)
. And what is f
is the function that was passed to sum
.
So calling sum(square)
just returns a function (sumF
) it haven’t executed anything (more over, you could assign that to a val
, instead of a def
). And when you call sumCubes(2, 3)
what happens if the following.
sumCubes(2, 3)
if (2 > 3) 0 else f(2) + sumF(2 + 1, 3) // By definition of sumF.
f(2) + sumF(2 + 1, 3) // By evaluation of if.
(2 * 2 * 2) + sumF(2 + 1, 3) // By definition of cube.
8 + sumF(2 + 1, 3) // By evaluation of *.
8 + (if (3 > 3) 0 else f(3) + sumF(3 + 1, 3)) // By definition of sumF.
8 + (f(3) + sumF(3 + 1, 3)) // By evaluation of if.
8 + ((3 * 3 * 3) + sumF(3 + 1, 3)) // By definition of cube.
8 + 27 + sumF(3 + 1, 3) // By evaluation of *.
8 + 27 + (if (4 > 3) 0 else f(4) + sumF(4 + 1, 3)) // By definition of sumF.
8 + 27 + 0 // By evaluation of if.
35 // By evaluation of +.