previous | index | next

Adding to the End of a List

Desired behavior:
          (add-to-end '(5 4 3 2) 1) ⇒ (5 4 3 2 1)
Q: Adding element elt to the empty list produces what list?

A: (elt)

Q: How do you add elt to the end of a nonempty list?
(Hint: Answer recursively in terms of the head and tail.)

A: Add elt to the end of the tail and cons the head onto that result.

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

previous | index | next