Contents    Page-10    Prev    Next    Page+10    Index   

Tail Recursive Reverse


(defun trrev (lst) (trrevb lst '()))

(defun trrevb (in out)
  (if (null in)
      out
      (trrevb (rest in)
              (cons (first in) out)) ) )

With a tail-recursive function, the unwinding of the recursion is all the same, so it can be compressed into one stack frame.


>(trrev '(a b c d))
  1> (TRREVB (A B C D) NIL)
    2> (TRREVB (B C D) (A))
      3> (TRREVB (C D) (B A))
        4> (TRREVB (D) (C B A))
          5> (TRREVB NIL (D C B A))
          <5 (TRREVB (D C B A))
        <4 (TRREVB (D C B A))
      <3 (TRREVB (D C B A))
    <2 (TRREVB (D C B A))
  <1 (TRREVB (D C B A))
(D C B A)