Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tailrec
- # tail-recursion-support by mokrates
- # use like this:
- #
- # @tailrecursive
- # def tailrecursive_function(foo, bar): ...
- #
- # the tail-recursive call
- # return tailrecursive_function(foo, bar)
- # translates to
- # return tailresult(tailrecursive_function, foo, bar)
- #
- # functions given to tailresult MUST be decorated @tailrecursive
- class tailresult:
- def __init__(self, f, *args, **kwargs):
- self.f = f
- self.args = args
- self.kwargs = kwargs
- def __repr__(self):
- return "<tailresult(%s,%s,%s)>" % (repr(self.f), repr(self.args), repr(self.kwargs))
- def tailrecursive(f):
- def taildecorator(*args, **kwargs):
- res = f(*args, **kwargs)
- while isinstance(res, tailresult):
- res = res.f.f(*res.args, **res.kwargs)
- return res
- taildecorator.f = f
- return taildecorator
- if __name__ == '__main__':
- def fak(x):
- if (x==1): return 1
- else: return fak(x-1)*x
- @tailrecursive
- def tr_fak(x,y):
- if y==0: return x
- else: return tailresult(tr_fak, x*y, y-1)
- print tr_fak(1,1000)
Advertisement
Add Comment
Please, Sign In to add comment