This is a dirty solution, but it might be interesting:
It is possible to implement "tail recursion"; this would solve the
problem for certain kinds of recursion; but will fail if the call is
not a tail call, and I think this code won't work, but some variations
would...
I toss it as an idea:
The code is taken from
http://code.activestate.com/recipes/474088
import sys
class TailRecurseException:
def __init__(self, args, kwargs):
self.args = args
self.kwargs = kwargs
def tail_call_optimized(g):
"""
This function decorates a function with tail call
optimization. It does this by throwing an exception
if it is it's own grandparent, and catching such
exceptions to fake the tail call optimization.
This function fails if the decorated
function recurses in a non-tail context.
"""
def func(*args, **kwargs):
f = sys._getframe()
if f.f_back and f.f_back.f_back \
and f.f_back.f_back.f_code == f.f_code:
raise TailRecurseException(args, kwargs)
else:
while 1:
try:
return g(*args, **kwargs)
except TailRecurseException, e:
args = e.args
kwargs = e.kwargs
func.__doc__ = g.__doc__
return func
@tail_call_optimized
def factorial(n, acc=1):
"calculate a factorial"
if n == 0:
return acc
return factorial(n-1, n*acc)
print factorial(10000)
prints a big, big number,
but doesn't hit the recursion limit.
@tail_call_optimized
def fib(i, current = 0, next = 1):
if i == 0:
return current
else:
return fib(i - 1, next, current + next)
print fib(10000)
also prints a big number,
but doesn't hit the recursion limit.
@tail_call_optimized
def say(something):
print something
say(something)
say('hello')
If I remember correctly, this code breaks and hangs the computer if
the tail is not a tail call; but there seems to be other solutions in
http://code.activestate.com/recipes/474088 that solve this problem
I would love if sage included a similar decorator; but am not sure of
the implications.
Another alternative is rewriting your code... to use iterations
instead of recursion whenever possible.
Peace.
-Adri'an.