Tail recursion: Difference between revisions

Content deleted Content added
Fixed claim that tail recursion is more efficient in time. This is implementation dependent, and is usually only a prefactor better for "reasonable" recursion depths. (Before stack thrashing.)
Description: Improved wording.
Line 4:
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 [[call 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 hugebe numbershuge, 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).
 
If several functions are ''mutually recursive'', meaning they each call one another, and each call they make to one another in an execution sequence uses a tail call, then tail call optimization will give a ''properly tail recursive'' implementation that does not consume stack space. Proper tail recursion optimization is required by the standard definitions of some programming languages, such as [[Scheme (programming language)|Scheme]].