而開啟尾遞歸優(yōu)化后, 就沒有新的調(diào)用棧生成了, 而是直接pop
bp指向的 _tail_recursion
函數(shù)的地址(pushq %rbp)然后返回,
仍舊用的是同一個(gè)調(diào)用棧!
存在的問(wèn)題
雖然尾遞歸優(yōu)化很好, 但python 不支持尾遞歸,遞歸深度超過(guò)1000時(shí)會(huì)報(bào)錯(cuò)
RuntimeError: maximum recursion depth exceeded
一個(gè)牛人想出的解決辦法
實(shí)現(xiàn)一個(gè) tail_call_optimized 裝飾器
#!/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 = kwargs