问题
I have written following code in C. Can we call it a tail recursive implementation?
#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.
回答1:
By definition your ackermann
function is a tail-recursive function as you're directly returning the result of the recursive case. Since no further logic depends on the result of your recursive call, the compiler can safely apply tail-recursion optimization.
回答2:
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. 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.
来源:https://stackoverflow.com/questions/33217360/can-this-implementation-of-ackermann-function-be-called-tail-recursive