When should you not use tail recursion

Simply said, tail recursion is a recursion where the compiler could replace the recursive call with a "goto" command, so the compiled version will not have to increase the stack depth.

Sometimes designing a tail-recursive function requires you need to create a helper function with additional parameters.

For example, this is not a tail-recursive function:

But this is a tail-recursive function:

because the compiler could rewrite the recursive function to a non-recursive one, using something like this (a pseudocode):

The rule for the compiler is very simple: When you find "", replace it with "". But this can be done only if the value returned by the recursive call is returned directly.

If all recursive calls in a function can be replaced like this, then it is a tail-recursive function.


answered Jan 10 '13 at 14:57