gpt4 book ai didi

recursion - 尾递归是否支持缩短其他函数调用的堆栈?

转载 作者:行者123 更新时间:2023-12-02 00:05:35 24 4
gpt4 key购买 nike

支持尾递归的语言能否将相同的技术应用于非递归函数调用?

例如,如果函数 foo 做的最后一件事是返回调用 bar 的值,语言可能会丢弃 foo 的值堆栈框架?是否有已知的语言可以实际执行此操作?

最佳答案

Erlang does :

Tail recursion as seen here is not making the memory grow because when the virtual machine sees a function calling itself in a tail position (the last expression to be evaluated in a function), it eliminates the current stack frame. This is called tail-call optimisation (TCO) and it is a special case of a more general optimisation named Last Call Optimisation (LCO).

LCO is done whenever the last expression to be evaluated in a function body is another function call. When that happens, as with TCO, the Erlang VM avoids storing the stack frame. As such tail recursion is also possible between multiple functions. As an example, the chain of functions a() -> b(). b() -> c(). c() -> a(). will effectively create an infinite loop that won't go out of memory as LCO avoids overflowing the stack. This principle, combined with our use of accumulators is what makes tail recursion useful.

关于recursion - 尾递归是否支持缩短其他函数调用的堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18593540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com