previous | index | next

List Processing Efficiency: Reversing Lists

Consider the problem of reversing the elements of a list:
           (reverse '(1 2 3 4 5)) ⇒ (5 4 3 2 1)
Q: What is the reverse of the empty list?

A: The empty list

Q: If you had the reverse of a list's tail, how would you get the reverse of the whole list?

A: Add the head of the list to the end of the reversed tail.

     (define reverse
       (lambda (lst)
         (if (null? lst)
             '()
             (add-to-end (reverse (cdr lst)) (car lst)))))

previous | index | next