3.3.1. Mutable List Structure
Exercise 3.12

Appending lists

The following procedure for appending lists was introduced in section 2.2.1 :

(define (append x y)
  (if (null? x)
      (cons (car x) (append (cdr x) y))))

Append forms a new list by successively consing the elements of x onto y . The procedure append! is similar to append , but it is a mutator rather than a constructor. It appends the lists by splicing them together, modifying the final pair of x so that its cdr is now y . (It is an error to call append! with an empty x .)

(define (append! x y)
  (set-cdr! (last-pair x) y)

Here last-pair is a procedure that returns the last pair in its argument:

(define (last-pair x)
  (if (null? (cdr x))
      (last-pair (cdr x))))

Consider the interaction

(define x (list 'a 'b))
(define y (list 'c 'd))
(define z (append x y))
(a b c d)
(cdr x)
(define w (append! x y))
(a b c d)
(cdr x)

What are the missing <response> s? Draw box-and-pointer diagrams to explain your answer.

There are no comments yet.

Authentication required

You must log in to post a comment.