According to Idea this function doesn't contain a ...
# announcements
b
According to Idea this function doesn't contain a tail call. Any idea why?
Copy code
tailrec fun increment(i: Int): Int =
    if (i == 3) i
    else i + increment(i + 1)
t
Because the last call is the
+
not the
increment
function call
a
what is a tail call
😂 1
e
lmgtfy:
b
@todd.ginsberg I factored the + out, but still got the same warning. What else could be wrong?
Copy code
tailrec fun increment(i: Int): Int =
    if (i == 3) i
    else {
        val j = i + 1
        i + increment(j)
    }
s
Tail recursion is when last action is evaluation of the same function. In your code for else branch last action is NOT
increment(j)
, but adding
i
to result of increment. Therefore, there is no tail recursion, as on stack should exist value of i and code should know about adding operation
☝️ 1
m
If you want to make that function tail recursive, you have to add an accumulator as a parameter. That will allow you to make the recursive call last. Something like this:
Copy code
fun increment(i: Int): Int {
  tailrec fun innerIncrement(i: Int, acc: Int): Int =
    if (i == 3) i + acc
    else innerIncrement(i + 1, acc + i)

  return innerIncrement(i, 0)
}
s
Copy code
tailrec fun increment(i: Int, acc: Int = 0): Int {
   return if (acc == 3) acc
  else {  
    val j = i + 1  
    increment(j, acc + j)
 }
}
m
The wrapper function is just to keep the function signature the same.
s
maybe that’s what you want
b
@marstran @sikri Thanks for your snippets. I think I got it now, cheers.
👍 1