Simple implementation of tail-call-elimination
Daniel Faken
dfaken at brandeis.edu
Wed Jun 5 09:49:18 EDT 2002
Hello,
Just thought I'd share this.
For more info. about tail-call-elimination, continuations, etc. see
the Scheme language or articles about functional programming in
Python.
Anyone have a suggestion for a better way to do this?
(more efficient, elegant, etc..)
This should be easy to implement in C, for speed.
cheers,
Daniel
dfaken at brandeis.edu
---------------
import types
# Tail-Recursion-Elimination tools
#
# Usage: include a keyword parameter with initial value 'TRE' in the
function(s)
# from which you wish to eliminate tail-recursion - e.g.
'cont=TRE'.
# Then, where you would normally use "return Fn(a,b,c..)",
instead
# call the keyword with the function and its arguments as
parameters
# - e.g. 'cont(Fn,a,b,c,...)'
# This allows TRE to control the program flow, and eliminate
deep recursion.
#
# Example:
# def factorial(n,acc=1,cont=TRE):
# if n <= 1: return acc
# else: return cont(factorial,n-1,acc*n)
#
# N.B. this is not yet set up for use with functions
# which accept keywords or return multiple values
TRE_magic = "TRE magic string"
def TREcont(fn, *rest): return (TRE_magic, fn, rest)
def TRE(fn, *rest):
x = fn(cont=TREcont, *rest)
while isinstance(x, types.TupleType) and (x[0] is TRE_magic):
x = x[1](*x[2])
return x
More information about the Python-list
mailing list