尾部调用优化有什么大不了的,为什么 Python 需要它?
显然,对于 Python 是否需要尾部调用优化 (TCO) 一直存在很大争议。 当有人向 Guido 发送了一份 SICP 副本时,事情就达到了紧要关头,因为他没有“明白”。 我和 Guido 处境相同。 我理解尾调用优化的概念。 我只是想不出 Python 真正需要它的任何原因。
为了让我更容易理解,使用 TCO 可以大大简化的代码片段是什么?
Apparently, there's been a big brouhaha over whether or not Python needs tail-call optimization (TCO). This came to a head when someone shipped Guido a copy of SICP, because he didn't "get it." I'm in the same boat as Guido. I understand the concept of tail-call optimization. I just can't think of any reason why Python really needs it.
To make this easier for me to understand, what would be a snippet of code that would be greatly simplified using TCO?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
就我个人而言,我非常重视尾调用优化; 但主要是因为它使递归与迭代一样高效(或者使迭代成为递归的子集)。 在简约语言中,您可以在不牺牲性能的情况下获得巨大的表达能力。
在“实用”语言(如 Python)中,OTOH,您通常对几乎所有可以想象的情况都有很多其他结构,因此它不太重要。 当然,考虑到不可预见的情况,拥有它总是一件好事。
Personally, I put great value on tail call optimization; but mainly because it makes recursion as efficient as iteration (or makes iteration a subset of recursion). In minimalistic languages you get huge expressive power without sacrificing performance.
In a 'practical' language (like Python), OTOH, you usually have a lot of other constructions for almost every situation imaginable, so it's less critical. It is always a good thing to have, to allow for unforeseen situations, of course.
如果您强烈希望将递归用于可以替代地表示为循环的事物,那么“尾部调用优化”确实是必须的。 然而,Python 的仁慈独裁者 (BDFL) Guido 坚信循环应该被表达为循环——所以他不会使用特殊情况的尾部调用(牺牲堆栈跟踪转储和调试规律性)。
If you intensely want to use recursion for things that might alternatively be expressed as loops, then "tail call optimization" is really a must. However, Guido, Python's Benevolent Dictator For Life (BDFL), strongly believes in loops being expressed as loops -- so he's not going to special-case tail calls (sacrificing stack-trace dumps and debugging regularity).
尾部调用优化使编写递归函数变得更容易,而不必担心堆栈溢出:
没有尾部-调用优化,使用大数字调用可能会溢出堆栈。
Tail-call optimization makes it easier to write recursive functions without worrying about a stack overflow:
Without tail-call optimization, calling this with a big number could overflow the stack.
Guido 在后续帖子中得到认可TCO 允许更清晰地将状态机实现为相互递归调用的函数集合。 然而,在同一篇文章中,他提出了一种同样清洁的替代解决方案,无需 TCO。
Guido recognized in a follow up post that TCO allowed a cleaner the implementation of state machine as a collection of functions recursively calling each other. However in the same post he proposes an alternative equally cleaner solution without TCO.