Skip to content

Instantly share code, notes, and snippets.

@zacharyvoase
Created July 18, 2009 15:03
Show Gist options
  • Save zacharyvoase/149579 to your computer and use it in GitHub Desktop.
Save zacharyvoase/149579 to your computer and use it in GitHub Desktop.
Simple tail recursion.
# -*- 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