Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Tail Recursion

Name: Anonymous 2011-10-19 21:09

How do i make this function tail recursive in java


public int fib(int n)
{
  return( n <= 1 ? n : fib(n-1) + fib(n-2) );
}

Name: Anonymous 2011-10-20 1:05

>>9
but it will eventually consume all memory
I'm of two minds on this. The shitposter in me wants to agree on the basis that all Java applications are designed to do just that, thus printing the tidy stack trace.

More seriously though, implementers don't feel right about doing this. It compromises the optimization (adding a factor of NaN overhead) since proper TCO executes in constant space. It also adds complexity to the code, all for the sake of recording the stack behavior of what is likely to be some short bodied calls anyway -- you won't save much space in the common case, you'll be slowing down all tail calls, and you will have complicated the code.

tl;dr -> Usually either you highly value the stack information in which case you kill off TCO or you are willing to sacrifice it for the memory savings. Going bipartisan just makes trouble, wastes time and and saves roughly nothing.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List