Previous: Setcdr, Up: Modifying Lists

5.6.3 Functions that Rearrange Lists

Here are some functions that rearrange lists destructively by modifying the cdrs of their component cons cells. These functions are destructive because they chew up the original lists passed to them as arguments, relinking their cons cells to form a new list that is the returned value.

See delq, in Sets And Lists, for another function that modifies cons cells.

— Function: nconc &rest lists

This function returns a list containing all the elements of lists. Unlike append (see Building Lists), the lists are not copied. Instead, the last cdr of each of the lists is changed to refer to the following list. The last of the lists is not altered. For example:

          (setq x '(1 2 3))
               ⇒ (1 2 3)
          (nconc x '(4 5))
               ⇒ (1 2 3 4 5)
          x
               ⇒ (1 2 3 4 5)

Since the last argument of nconc is not itself modified, it is reasonable to use a constant list, such as '(4 5), as in the above example. For the same reason, the last argument need not be a list:

          (setq x '(1 2 3))
               ⇒ (1 2 3)
          (nconc x 'z)
               ⇒ (1 2 3 . z)
          x
               ⇒ (1 2 3 . z)

However, the other arguments (all but the last) must be lists.

A common pitfall is to use a quoted constant list as a non-last argument to nconc. If you do this, your program will change each time you run it! Here is what happens:

          (defun add-foo (x)            ; We want this function to add
            (nconc '(foo) x))           ;   foo to the front of its arg.
          
          (symbol-function 'add-foo)
               ⇒ (lambda (x) (nconc (quote (foo)) x))
          
          (setq xx (add-foo '(1 2)))    ; It seems to work.
               ⇒ (foo 1 2)
          (setq xy (add-foo '(3 4)))    ; What happened?
               ⇒ (foo 1 2 3 4)
          (eq xx xy)
               ⇒ t
          
          (symbol-function 'add-foo)
               ⇒ (lambda (x) (nconc (quote (foo 1 2 3 4) x)))