Created
July 4, 2014 08:57
-
-
Save wcp1231/bdb6e5b003c264b1632a to your computer and use it in GitHub Desktop.
Trampoline in python
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
# python has no tail recursion optimization. | |
def f(n): | |
if n == 0: return 1 | |
return n * f(n-1) | |
f(5000) | |
# > RuntimeError: maximum recursion depth exceeded | |
# so, we can use trampoline | |
def f(n): | |
from types import FunctionType | |
def ff(n, sum): | |
if n == 0: return sum | |
return lambda: ff(n-1, n*sum) | |
def do(n): | |
fn = ff(n, 1) | |
while fn.__class__ == FunctionType: | |
fn = fn() | |
return fn | |
return do(n) | |
f(5000) | |
# > 42285779266055435222010642002335...... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment