Share

Xoltar Toolkit

Tracker: Feature Requests

5 Tail recursion - ID: 427603
Last Update: Tracker Item Submitted ( nobody )

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.


Nobody/Anonymous ( nobody ) - 2001-05-26 20:47

5

Open

None

Nobody/Anonymous

None

None

Public


Comments




Log in to comment.

No follow-up comments have been posted.

Attached File

No Files Currently Attached

Change

No changes have been made to this artifact.