Nested Scopes ... next tail recursion?
Richard Davies
richardd at pobox.com
Sat May 26 14:40:58 EDT 2001
> I wonder if there is any chance of getting
> tail recusion handled properly in the future?
Well, regardless of the language, you can write it yourself.
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!
Richard.
More information about the Python-list
mailing list