Contents    Page-10    Prev    Next    Page+10    Index   

Constructive Tail Recursive Reverse

reverse makes a new linked list whose elements are in the reverse order of the original list; the original is unchanged.


(reverse '(a b c))      ->  (c b a)
This function takes advantage of the fact that cons creates a list in the reverse order of the conses that are done, i.e. cons is like a push onto a stack.


(defn trrevb [lst answer]
  (if (empty? lst)
      answer
      (trrevb (rest lst)
              (cons (first lst) answer)) ) )

(defn trrev [lst] (trrevb lst '()))