Next: , Up: Modifying Lists


11.6.1 Altering List Elements with setcar

Changing the car of a cons cell is done with setcar. When used on a list, setcar replaces one element of a list with a different element.

— Function: setcar cons-cell object

This function stores object as the new car of cons-cell, replacing its previous car. It returns the value object. For example:

          (setq x '(1 2))
               ⇒ (1 2)
          (setcar x 4)
               ⇒ 4
          x
               ⇒ (4 2)

When a cons cell is part of the shared structure of several lists, storing a new car into the cons changes one element of each of these lists. Here is an example:

     ;; Create two lists that are partly shared.
     (setq x1 '(a b c))
          ⇒ (a b c)
     (setq x2 (cons 'z (cdr x1)))
          ⇒ (z b c)
     
     ;; Replace the car of a shared link.
     (setcar (cdr x1) 'foo)
          ⇒ foo
     x1                           ; Both lists are changed.
          ⇒ (a foo c)
     x2
          ⇒ (z foo c)
     
     ;; Replace the car of a link that is not shared.
     (setcar x1 'baz)
          ⇒ baz
     x1                           ; Only one list is changed.
          ⇒ (baz foo c)
     x2
          ⇒ (z foo c)

Here is a graphical depiction of the shared structure of the two lists in the variables x1 and x2, showing why replacing b changes them both:

             ___ ___        ___ ___      ___ ___
     x1---> |___|___|----> |___|___|--> |___|___|--> nil
              |        -->   |            |
              |       |      |            |
               --> a  |       --> b        --> c
                      |
            ___ ___   |
     x2--> |___|___|--
             |
             |
              --> z

Here is an alternative form of box diagram, showing the same relationship:

     x1:
      --------------       --------------       --------------
     | car   | cdr  |     | car   | cdr  |     | car   | cdr  |
     |   a   |   o------->|   b   |   o------->|   c   |  nil |
     |       |      |  -->|       |      |     |       |      |
      --------------  |    --------------       --------------
                      |
     x2:              |
      --------------  |
     | car   | cdr  | |
     |   z   |   o----
     |       |      |
      --------------