is there a way, to make a method tailrecursive. wh...
# announcements
t
is there a way, to make a method tailrecursive. when the return is nested in a return?
k
Can you share the code?
👍 1
t
Sorry i meant the recursive step, not the return
I c cannot share the code itself, but in the end its traversing a tree where i calculate a value based on its children, so the pseudo code looks like:
Copy code
fun caclculate(treeNode: TreeNode): Int {
  val baseValue = 10
  var returnValue;
  for (child: treeNode.Children) {
    returnValue += calculate(child) 
  }
return returnValue + baseValue;
}
d
That cannot work. Tail recursion is called that, because the recursive call must be the last thing in the function
Otherwise the recursion cannot be unrolled into a flat loop by the compiler
t
yeah im aware of that, but i wonder i f there are some clever tricks to restructure the code to rget rid of it, that i am not aware of 😉
d
You can implement a Queue of nodes still to do. But that is effectively just implementing your own call stack.
Although most likely more lightweight
t
general solution is to add an accumulator
Copy code
tailrec fun calculate(treeNode: TreeNode, acc: Int){
// logic
return calculate(otherTreeNode, acc+resultOfLogic)
}
👍 1
t
oh an accumulator. thats clever. i'll check that. thank you!
t
have fun 🙂