Tail recursion

From Rosetta Code
Revision as of 16:28, 30 September 2008 by rosettacode>Mwn3d (Not-too-in-depth summary of tail recursion. Could probably use more information from a CS person or a Scheme person.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Tail recursion is a specific type of recursion where the recursion call is the last call in the function. Because tail recursive functions can easily and automatically be transformed into a normal iterative functions, tail recursion is used in languages like Scheme to optimize function calls, while still keeping the function definitions small and easy to read. The actual optimization transforms recursive calls into simple branches (or jumps) with logic to change the arguments for the next run through the function.

The benefits of this optimization are primarily stack related. Transforming recursive functions into iterative functions can save memory and time. Because memory can be saved, more complex calls can be evaluated without overflowing the stack.