Tail Call Optimization Decorator (Python recipe)
来源:互联网 发布:12315可以投诉淘宝小二 编辑:程序博客网 时间:2024/06/05 23:48
This decorator implements tail call optimization through stack introspection.
#!/usr/bin/env python2.4# This program shows off a python decorator(# which implements tail call optimization. It# does this by throwing an exception if it is # it's own grandparent, and catching such # exceptions to recall the stack.import sysclass TailRecurseException: def __init__(self, args, kwargs): self.args = args self.kwargs = kwargsdef tail_call_optimized(g): """ This function decorates a function with tail call optimization. It does this by throwing an exception if it is it's own grandparent, and catching such exceptions to fake the tail call optimization. This function fails if the decorated function recurses in a non-tail context. """ def func(*args, **kwargs): f = sys._getframe() if f.f_back and f.f_back.f_back \ and f.f_back.f_back.f_code == f.f_code: raise TailRecurseException(args, kwargs) else: while 1: try: return g(*args, **kwargs) except TailRecurseException, e: args = e.args kwargs = e.kwargs func.__doc__ = g.__doc__ return func@tail_call_optimizeddef factorial(n, acc=1): "calculate a factorial" if n == 0: return acc return factorial(n-1, n*acc)print factorial(10000)# prints a big, big number,# but doesn't hit the recursion limit.@tail_call_optimizeddef fib(i, current = 0, next = 1): if i == 0: return current else: return fib(i - 1, next, current + next)print fib(10000)# also prints a big number,# but doesn't hit the recursion limit.
0 0
- Tail Call Optimization Decorator (Python recipe)
- Tail call optimization in Scala
- 尾调用优化(Tail Call Optimization)
- 关于 Tail Calls Optimization
- 函数尾调用优化(Tail-call Optimization)对DTrace return probe的影响
- x64 Tail Call Elimination
- python django recipe app
- Prototype pattern (Python recipe)
- 尾递归(Tail recursion / Tail call)
- python decorator
- python decorator
- python decorator
- python decorator
- Python - Decorator
- Python decorator
- python decorator
- python decorator
- Python Decorator
- java实例化对象时程序运行顺序
- [BEROR]CodeSign error: code signing is required for product type 'Application' in SDK 'iOS 7.1'
- Valid Sudoku
- 2014华为机试题1:亮着电灯的盏数
- 全功能合并单元格js
- Tail Call Optimization Decorator (Python recipe)
- 【麦子学院】攻克安全漏洞,协助Android前行
- mysql主主备份在不停机的情况下修改另外一个数据库服务器
- ORA-00904:标识符无效 oracle view 列名 大小写问题
- LeetCode | Permutation Sequence(找到全排列中的第k个排列)
- 移动互联网创业交流
- python 时间戳处理
- 临时文档8--好恶心的代码
- 《数据结构与算法JavaScript描述》