Help understanding tail-recursive function


#1

I’m new to Scala and FP. I’m learning by going through Functional Programming Principles in Scala on Coursera

I’m trying to understand the following function, sum(), which sums all the integers between a and b:

def sum(f: Int => Int, a: Int, b: Int): Int = {

  def loop(x: Int, acc: Int): Int = {
     if (x > b) acc
     else loop(x + 1, acc + f(x))
  }

  loop(a, 0)  
}

sum(x => x, 1, 3)

The answer is 6, but if I try going through the function step by step I don’t arrive at the same answer:
First iteration of loop takes (1 + 1, 0 +1) or (2, 1) as arguments.
Second iteration of loop takes (2 + 1, 1 + 2) or (3, 3) as arguments.

After which the condition (x > b) or (3 > 3) is no longer false and thus the function should return acc which at this point is 3 not 6 which would be the correct answer.

What am I missing?

Thank you!


#2

This is where you make a mistake. 3 > 3 is still false.


#3

BTW,why is first argument(f) needed here?


#4

Because it’s used in this line:
else loop(x + 1, acc + f(x))