简体   繁体   English

这种Ackermann函数的实现可以称为尾递归吗?

[英]Can this implementation of Ackermann function be called tail recursive?

I have written following code in C. Can we call it a tail recursive implementation? 我在C中编写了以下代码。我们可以称之为尾递归实现吗?

#include <stdio.h>

int ackermann(unsigned int *m, unsigned int *n, unsigned int* a, int* len)
{
  if(!*m && *len == -1) {
    return ++*n;
  }
  else if(!*m && *len >= 0) {
    ++*n;
    *m = a[(*len)--];
  }
  else if(*n == 0) {
    --*m;
    *n = 1;
  } else {
    ++*len;
    a[*len] = *m - 1;
    --*n;
  }
  return ackermann(m, n, a, len);
}

int main()
{
  unsigned int m=4, n=1;
  unsigned int a[66000];
  int len = -1;

  for (m = 0; m <= 4; m++)
    for (n = 0; n < 6 - m; n++) {
      unsigned int i = m;
      unsigned int j = n;
      printf("A(%d, %d) = %d\n", m, n, ackermann(&i, &j, a, &len));
    }

  return 0;
}

If it is not tail-recursive please suggest ways to make it so. 如果它不是尾递归,请建议如何做到这一点。 Any reference to a tail recursive version of Ackermann would be nice in C/C++/Java or non-functional programming language. 任何对Ackermann的尾递归版本的引用在C / C ++ / Java或非函数式编程语言中都会很好。

Your function uses a data structure to do it's backtracking so while it is a tail recursive function it definitely isn't a simple recursive or iterative process. 你的函数使用数据结构进行回溯,所以当它是一个尾递归函数时,它肯定不是一个简单的递归或迭代过程。 The array a takes the role as a recursion stack. 数组a充当递归堆栈。 You could write out the recursive call alltogether: 你可以写出所有的递归调用:

int ackermann(unsigned int *m, unsigned int *n, unsigned int* a, int* len)
{
  while (*m || *len != -1) {
      if(!*m && *len >= 0) {
        *n++;
        *m = a[(*len)--];
      } else if(*n == 0) {
        *m--;
        *n = 1;
      } else {
        ++*len;
        a[*len] = *m - 1;
        *n--;
      }
  }
  return ++*n;
}

Still without any recursive call I consider this a recursive process. 仍然没有任何递归调用我认为这是一个递归过程。

By definition your ackermann function is a tail-recursive function as you're directly returning the result of the recursive case. 根据定义,你的ackermann函数一个尾递归函数,因为你直接返回递归情况的结果。 Since no further logic depends on the result of your recursive call, the compiler can safely apply tail-recursion optimization. 由于没有进一步的逻辑取决于递归调用的结果,编译器可以安全地应用尾递归优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM