最终的尾调用递归问题

发布于 2024-08-22 06:59:58 字数 228 浏览 6 评论 0原文

参加这次惨败问题,我想向整个社区提出这个问题。

基于.Net的代码在什么场景下会应用尾调用优化?

请用可靠的、最新的来源或可重复的实验来支持你的答案。

After participating in the debate in this fiascoquestion, I would like to posit the question before the entire community.

In what scenarios will tail-call optimization be applied to .Net-based code?

Please support your answers with reliable, up-to-date sources or reproducible experiments.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

溺深海 2024-08-29 06:59:58

根据 Don Syme 等人撰写的“Expert F#”,F# 进行尾调用优化。我似乎记得在 Eric Lippert 的博客上读到 C# 编译器(任何版本)都没有。如果我错了,请纠正我,埃里克。在所有情况下,当最后一条指令是调用方法时,都可以进行尾部调用优化。这通常是方法本身的递归调用,但并非必须如此。可以进行优化,因为可以保证不再需要当前堆栈帧。但如果事后只需要进行简单的操作,则无法进行优化。

int Fib(int n)
{
  if(n < 2)
     return 1;

  return Fib(n-1) + Fib(n-2);
}

这无法进行尾部调用优化,因为在最后一次调用 Fib 返回之前无法评估 +。 (实际上,我认为这也是 Expert F# 中使用的示例,但不确定。)

int Fib(int n, int a, int b)
{
  if(n == 0)
    return a+b;
  return Fib(n-1,a+b,a);
}

此版本可以进行尾调用优化,因为所有参数都在最后一次调用 Fib 之前评估,并且没有存在要在调用后执行的操作,因此可以丢弃当前堆栈帧。

According to "Expert F#" written by Don Syme et al., F# does tail call optimization. I seem to remember reading on Eric Lippert's blog that the C# compiler (any version) does not. Correct me if I'm wrong, Eric. In all cases tail-call optimizations can be done when the last instruction is to call a method. This will often be a recursive call of the method itself but does not need to be. The optimization can be done since it's guaranteed that the current stack frame is no longer needed. However if just a simple operation has to be performed afterwards the optimization cannot be performed.

int Fib(int n)
{
  if(n < 2)
     return 1;

  return Fib(n-1) + Fib(n-2);
}

This cannot be tail call optimized because + cannot be evaluated before the last call to Fib returns. (Actually I think this is the example used in Expert F# as well but not sure on that one.)

int Fib(int n, int a, int b)
{
  if(n == 0)
    return a+b;
  return Fib(n-1,a+b,a);
}

This version can be tail call optimized since all the arguments are evaluated before the last call to Fib and no operations exist to be performed after the call so the current stack frame can be discarded.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文