Tail recursion to while iteration in 2 easy steps

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Wed Oct 2 04:23:46 EDT 2013


rusi <rustompmody at gmail.com> writes:

> On Wednesday, October 2, 2013 3:00:41 AM UTC+5:30, Terry Reedy wrote:
>> Part of the reason that Python does not do tail call optimization is 
>> that turning tail recursion into while iteration is almost trivial, once 
>> you know the secret of the two easy steps. Here it is.
>
> What happens for mutual tail recursive code like this
>
> def isodd(x) : return False if x==0 else iseven(x-1)
> def iseven(x): return True if x==0 else isodd(x-1)

It takes one step of inlining to make Terry's technique applicable.

(Actually, out of curiosity, I tried this with gcc 4.6.3: the compiler
does 16 levels of inlining, plus tail call optimization. The final code
has no call.)

-- Alain.



More information about the Python-list mailing list