I'm following a Coursera course for functional programming in Scala so that I can learn the language.
They introduced the concept of tail-recursive functions and defined them basically as a function that ends in a call to itself. But then they show this as the worked example:
def sum(f: Int => Int)(a: Int, b: Int): Int = {
def loop(a: Int, acc: Int): Int = {
if (a > b) acc
else loop(a + 1, f(a) + acc)
}
loop(a, 0)
}
If I annotate sum with @tailrec, I get an error because the IDE (IntelliJ) does not consider it to be tail recursive.
Is sum called tail-recursive here, or is the inner implementation "loop" the thing that is considered to be tail recursive in this case?
You're right.
sum
needs to call itself otherwise Scala will complain with:If you tell compiler where exactly it is, by moving the
@tailrec
to where the tail recursion is:Then the compiler'll be satisfied it is tail-recursion optimised.