Next: , Previous: Selecting List Components, Up: Lists


7.4 Cutting and Pasting Lists

— procedure: sublist list start end

Start and end must be exact integers satisfying

          0 <= start <= end <= (length list)

sublist returns a newly allocated list formed from the elements of list beginning at index start (inclusive) and ending at end (exclusive).

— procedure: list-head list k

Returns a newly allocated list consisting of the first k elements of list. K must not be greater than the length of list.

We could have defined list-head this way:

          (define (list-head list k)
            (sublist list 0 k))
— procedure: list-tail list k

Returns the sublist of list obtained by omitting the first k elements. The result, if it is not the empty list, shares structure with list. K must not be greater than the length of list.

— procedure: append list ...

Returns a list consisting of the elements of the first list followed by the elements of the other lists.

          (append '(x) '(y))                       (x y)
          (append '(a) '(b c d))                   (a b c d)
          (append '(a (b)) '((c)))                 (a (b) (c))
          (append)                                 ()

The resulting list is always newly allocated, except that it shares structure with the last list argument. The last argument may actually be any object; an improper list results if the last argument is not a proper list.

          (append '(a b) '(c . d))                 (a b c . d)
          (append '() 'a)                          a
— procedure: append! list ...

Returns a list that is the argument lists concatenated together. The arguments are changed rather than copied. (Compare this with append, which copies arguments rather than destroying them.) For example:

          (define x '(a b c))
          (define y '(d e f))
          (define z '(g h))
          (append! x y z)                          (a b c d e f g h)
          x                                        (a b c d e f g h)
          y                                        (d e f g h)
          z                                        (g h)
— procedure: last-pair list

Returns the last pair in list, which may be an improper list. last-pair could have been defined this way:

          (define last-pair
            (lambda (x)
              (if (pair? (cdr x))
                  (last-pair (cdr x))
                  x)))
— procedure: except-last-pair list
— procedure: except-last-pair! list

These procedures remove the last pair from list. List may be an improper list, except that it must consist of at least one pair. except-last-pair returns a newly allocated copy of list that omits the last pair. except-last-pair! destructively removes the last pair from list and returns list. If the cdr of list is not a pair, the empty list is returned by either procedure.