What is tail recursion?

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

    Recursion means a function calling itself. For example:

    (define (un-ended name)
      (un-ended 'me)
      (print "How can I get here?"))
    

    Tail-Recursion means the recursion that conclude the function:

    (define (un-ended name)
      (print "hello")
      (un-ended 'me))
    

    See, the last thing un-ended function (procedure, in Scheme jargon) does is to call itself. Another (more useful) example is:

    (define (map lst op)
      (define (helper done left)
        (if (nil? left)
            done
            (helper (cons (op (car left))
                          done)
                    (cdr left))))
      (reverse (helper '() lst)))
    

    In the helper procedure, the LAST thing it does if the left is not nil is to call itself (AFTER cons something and cdr something). This is basically how you map a list.

    The tail-recursion has a great advantage that the interpreter (or compiler, dependent on the language and vendor) can optimize it, and transform it into something equivalent to a while loop. As matter of fact, in Scheme tradition, most "for" and "while" loop is done in a tail-recursion manner (there is no for and while, as far as I know).

提交回复
热议问题