Python実装に最適化テールトーン
「Pythonで使用リターン +関数名は()」のすぐ関数呼び出しの現在の関数の終了後、すなわち末尾呼び出しを達成することができます。
しかし、Pythonは1000年だけで放水は、エラーを超えることができます。
以下は、従来のテールトーンの例です。
def a(e):
print('%s'%e)
return a(e + 1)
a(1)
結果:
1
2
3
...
995
996
RecursionError: maximum recursion depth exceeded while calling a Python object
エラーは、後に1,000以上の、それ以上の放水の放水深さであろう。
牛は解決策を考え出しました
次のコードは、(のpython3 +ため)デコレータを定義します
# 低版本Python改成 class TailRecurseException:
class TailRecurseException(BaseException):
def __init__(self, args, kwargs):
self.args = args
self.kwargs = kwargs
def 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()
# 为什么是grandparent, 函数默认的第一层递归是父调用,
# 对于尾递归, 不希望产生新的函数调用(即:祖父调用),
# 所以这里抛出异常, 拿到参数, 退出被修饰函数的递归调用栈!
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)
# 低版本Python改成 except TailRecurseException, e:
except TailRecurseException as e:
# 捕获异常, 拿到参数, 退出被修饰函数的递归调用栈
args = e.args
kwargs = e.kwargs
func.__doc__ = g.__doc__
return func
次のように上記の例は、次に読み出されます。
@tail_call_optimized
def a(e):
print('%s'%e)
return a(e + 1)
a(1)
# 实际使用时注意加停止调用的条件,否则会一直循环调用