Common Lisp the Language, 2nd Edition

Next: Substitution of Expressions Up: Lists Previous: Lists

# 15.3. Alteration of List Structure

The functions `rplaca` and `rplacd` may be used to make alterations in already existing list structure, that is, to change the car or cdr of an existing cons. One may also use `setf` in conjunction with `car` and `cdr`.

The structure is not copied but is destructively altered; hence caution should be exercised when using these functions, as strange side effects can occur if portions of list structure become shared. The `nconc`, `nreverse`, `nreconc`, and `nbutlast` functions, already described, have the same property, as do certain of the generic sequence functions such as `delete`. However, they are normally not used for this side effect; rather, the list-structure modification is purely for efficiency, and compatible non-modifying functions are provided.

[Function]
`rplaca x y`

`(rplaca x y)` changes the car of x to y and returns (the modified) x. x must be a cons, but y may be any Lisp object. For example:

    (setq g '(a b c))
    (rplaca (cdr g) 'd) => (d c)
    Now g => (a d c)

[Function]
`rplacd x y`

`(rplacd x y)` changes the cdr of x to y and returns (the modified) x. x must be a cons, but y may be any Lisp object. For example:

    (setq x '(a b c))
    (rplacd x 'd) => (a . d)
    Now x => (a . d)

The functions `rplaca` and `rplacd` go back to the earliest origins of Lisp, along with `car`, `cdr`, and `cons`. Nowadays, however, they seem to be falling by the wayside. More and more Common Lisp programmers use `setf` for nearly all structure modifications: `(rplaca x y)` is rendered as `(setf (car x) y)` or perhaps as `(setf (first x) y)`. Even more likely is that a `defstruct` structure or a CLOS class is used in place of a list, if the data structure is at all complicated; in this case `setf` is used with a slot accessor.

Next: Substitution of Expressions Up: Lists Previous: Lists