Menu

#2 Tail recursion

open
nobody
None
5
2001-05-26
2001-05-26
Anonymous
No

Some kind of support for tail recursion would be good.
As a proof it's possible, here's my implementation
(from comp.lang.python in a thread from about two
weeks ago, entitled "Nested Scopes ... next tail
recursion?"):

Consider a recursive function:

def recursivefunction(i):
if i==0:
return "bottom"
else:
return recursivefunction(i-1)

On my system this works for small i, but the
stack overflows by i=1000.

We now make the definition (attempting to support
making fairly general functions with fairly general
argument lists tail recursive):

from __future__ import nested_scopes
from types import DictType

def tailrecursedef(f):
def g(*a, **b):
r = apply(f, a, b)
while type(r)==DictType and
r.has_key('tailrecurse'):
r = apply(f, r['tailrecurse'][0],
r['tailrecurse'][1])
else:
return r
return g

following which we can rewrite in tail recursive form:

def bit(i):
if i==0:
return "bottom"
else:
return {'tailrecurse': ((i-1,),{})}

tailrecursivefunction = tailrecursedef(bit)

and tailrecursivefunction(100000) is fine!

However, I'm sure that it's possible to do better than
this - make the syntax a bit nicer and add support for
your closures, etc.

Discussion


Log in to post a comment.