Tail recursion: Difference between revisions

Content deleted Content added
Line 2:
 
==Description==
When a function is called, the computer must "remember" the place it was called from, the ''[[return address]]'', so that it can return to that ___location with the result once the call is complete. Typically, this information is saved on the stack, a simple list of return locations in order of the times that the call locations they describe were reached. Sometimes, the last thing that a function does after completing all other operations is to simply call a function, possibly itself, and return its result. With tail recursion, there is no need to remember the place we are calling from — instead, we can leave the stack alone, and the newly called function will return its result directly to the ''original'' caller. Converting a call to a branch or jump in such a case is called a ''tail call optimization''. Note that the tail call doesn't have to appear lexically after all other statements in the source code; it is only important that its result be immediately returned, since the calling function will never get a chance to do anything after the call if the optimization is performed.
 
For normal, non-recursive function calls, this is usually a [[micro-optimization]] that saves little time and space, since there are not that many different functions available to call. When dealing with recursive or mutually recursive functions, however, the stack space and the number of returns saved can grow to huge numbers, since a function can call itself, directly or indirectly, a huge number of times. In fact, it often asymptotically reduces stack space requirements from linear, or [[Big-O notation|O]](n), to constant, or [[Big-O notation|O]](1).