What is tail recursion?

前端 未结 28 3574
一个人的身影
一个人的身影 2020-11-21 05:03

Whilst starting to learn lisp, I\'ve come across the term tail-recursive. What does it mean exactly?

28条回答
  •  醉话见心
    2020-11-21 05:20

    An important point is that tail recursion is essentially equivalent to looping. It's not just a matter of compiler optimization, but a fundamental fact about expressiveness. This goes both ways: you can take any loop of the form

    while(E) { S }; return Q
    

    where E and Q are expressions and S is a sequence of statements, and turn it into a tail recursive function

    f() = if E then { S; return f() } else { return Q }
    

    Of course, E, S, and Q have to be defined to compute some interesting value over some variables. For example, the looping function

    sum(n) {
      int i = 1, k = 0;
      while( i <= n ) {
        k += i;
        ++i;
      }
      return k;
    }
    

    is equivalent to the tail-recursive function(s)

    sum_aux(n,i,k) {
      if( i <= n ) {
        return sum_aux(n,i+1,k+i);
      } else {
        return k;
      }
    }
    
    sum(n) {
      return sum_aux(n,1,0);
    }
    

    (This "wrapping" of the tail-recursive function with a function with fewer parameters is a common functional idiom.)

提交回复
热议问题