https://kotlinlang.org logo
#announcements
Title
# announcements
b

bascan

11/19/2019, 4:48 PM
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

todd.ginsberg

11/19/2019, 4:53 PM
Because the last call is the
+
not the
increment
function call
a

Ashutosh Panda

11/19/2019, 4:54 PM
what is a tail call
😂 1
e

eekboom

11/19/2019, 4:55 PM
lmgtfy:
b

bascan

11/19/2019, 5:00 PM
@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

sikri

11/19/2019, 5:01 PM
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

marstran

11/19/2019, 5:10 PM
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

sikri

11/19/2019, 5:10 PM
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

marstran

11/19/2019, 5:10 PM
The wrapper function is just to keep the function signature the same.
s

sikri

11/19/2019, 5:10 PM
maybe that’s what you want
b

bascan

11/19/2019, 5:15 PM
@marstran @sikri Thanks for your snippets. I think I got it now, cheers.
👍 1
4 Views