What is tail recursion?

前端 未结 28 3572
一个人的身影
一个人的身影 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:26

    Instead of explaining it with words, here's an example. This is a Scheme version of the factorial function:

    (define (factorial x)
      (if (= x 0) 1
          (* x (factorial (- x 1)))))
    

    Here is a version of factorial that is tail-recursive:

    (define factorial
      (letrec ((fact (lambda (x accum)
                       (if (= x 0) accum
                           (fact (- x 1) (* accum x))))))
        (lambda (x)
          (fact x 1))))
    

    You will notice in the first version that the recursive call to fact is fed into the multiplication expression, and therefore the state has to be saved on the stack when making the recursive call. In the tail-recursive version there is no other S-expression waiting for the value of the recursive call, and since there is no further work to do, the state doesn't have to be saved on the stack. As a rule, Scheme tail-recursive functions use constant stack space.

提交回复
热议问题