|
1 | | -"""Provides decorator to deal with tail calls in recursive function.""" |
| 1 | +"""Provides decorators to deal with tail calls in recursive functions.""" |
| 2 | + |
| 3 | +from collections import namedtuple |
2 | 4 |
|
3 | 5 |
|
4 | 6 | class tco(object): |
@@ -44,3 +46,90 @@ def __call__(self, *args, **kwargs): |
44 | 46 | if callable(act): |
45 | 47 | action = act |
46 | 48 | kwargs = result[2] if len(result) > 2 else {} |
| 49 | + |
| 50 | + |
| 51 | +class stackless(object): |
| 52 | + """Provides a "stackless" (constant Python stack space) recursion |
| 53 | + decorator for generators. |
| 54 | +
|
| 55 | + Invoking as f() creates the control structures. Within a |
| 56 | + function, only use `yield f.call()` and `yield f.tailcall()`. |
| 57 | +
|
| 58 | + Usage examples: |
| 59 | +
|
| 60 | + Tail call optimised recursion with tailcall(): |
| 61 | +
|
| 62 | + @recur.stackless |
| 63 | + def fact(n, acc=1): |
| 64 | + if n == 0: |
| 65 | + yield acc |
| 66 | + return |
| 67 | + yield fact.tailcall(n-1, n*acc) |
| 68 | +
|
| 69 | + Non-tail recursion with call() uses heap space so won't overflow: |
| 70 | +
|
| 71 | + @recur.stackless |
| 72 | + def fib(n): |
| 73 | + if n == 0: |
| 74 | + yield 1 |
| 75 | + return |
| 76 | + if n == 1: |
| 77 | + yield 1 |
| 78 | + return |
| 79 | + yield (yield fib.call(n-1)) + (yield fib.call(n-2)) |
| 80 | +
|
| 81 | + Mutual recursion also works: |
| 82 | +
|
| 83 | + @recur.stackless |
| 84 | + def is_odd(n): |
| 85 | + if n == 0: |
| 86 | + yield False |
| 87 | + return |
| 88 | + yield is_even.tailcall(n-1) |
| 89 | +
|
| 90 | + @recur.stackless |
| 91 | + def is_even(n): |
| 92 | + if n == 0: |
| 93 | + yield True |
| 94 | + return |
| 95 | + yield is_odd.tailcall(n-1) |
| 96 | +
|
| 97 | + """ |
| 98 | + |
| 99 | + __slots__ = "func", |
| 100 | + |
| 101 | + Thunk = namedtuple("Thunk", ("func", "args", "kwargs", "is_tailcall")) |
| 102 | + |
| 103 | + def __init__(self, func): |
| 104 | + self.func = func |
| 105 | + |
| 106 | + def call(self, *args, **kwargs): |
| 107 | + return self.Thunk(self.func, args, kwargs, False) |
| 108 | + |
| 109 | + def tailcall(self, *args, **kwargs): |
| 110 | + return self.Thunk(self.func, args, kwargs, True) |
| 111 | + |
| 112 | + def __call__(self, *args, **kwargs): |
| 113 | + s = [self.func(*args, **kwargs)] |
| 114 | + r = [] |
| 115 | + v = None |
| 116 | + while s: |
| 117 | + try: |
| 118 | + if r: |
| 119 | + v = s[-1].send(r[-1]) |
| 120 | + r.pop() |
| 121 | + else: |
| 122 | + v = next(s[-1]) |
| 123 | + except StopIteration: |
| 124 | + s.pop() |
| 125 | + continue |
| 126 | + |
| 127 | + if isinstance(v, self.Thunk): |
| 128 | + g = v.func(*v.args, **v.kwargs) |
| 129 | + if v.is_tailcall: |
| 130 | + s[-1] = g |
| 131 | + else: |
| 132 | + s.append(g) |
| 133 | + else: |
| 134 | + r.append(v) |
| 135 | + return r[0] if r else None |
0 commit comments