Created
July 18, 2009 15:03
-
-
Save zacharyvoase/149579 to your computer and use it in GitHub Desktop.
Simple tail recursion.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# Copyleft 2058 Zachary Voase | |
# Licensed under the WTFPL. Google it. | |
from functools import wraps | |
class call(object): | |
__slots__ = ('function', 'args', 'kwargs') | |
def __init__(self, function, *args, **kwargs): | |
self.function = function | |
self.args = args | |
self.kwargs = kwargs | |
def __call__(self): | |
return self.function(*self.args, **self.kwargs) | |
def tailrecursive(function): | |
@wraps(function) | |
def wrapper(*args, **kwargs): | |
result = function(*args, **kwargs) | |
while isinstance(result, call): | |
if result.function is wrapper: | |
result.function = wrapper.function | |
result = result() | |
return result | |
wrapper.function = function | |
return wrapper | |
@tailrecursive | |
def factorial(n, current=1): | |
if n <= 0: | |
return current | |
return call(factorial, n - 1, current=(current * n)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment