Skip to main content

rplaca, rplacd

rplaca, rplacd Function

Syntax:

rplaca cons object → cons

rplacd cons object → cons

Pronunciation:

rplaca: [ r—e plak* ] or [ r* plak* ]

rplacd: [ r—e plakd* ] or [ r* plakd* ] or [ r—e plakd—e ] or [ r* plakd—e ]

Arguments and Values:

cons—a cons.

object—an object.

Description:

rplaca replaces the car of the cons with object.

rplacd replaces the cdr of the cons with object.

Examples:

(defparameter \*some-list\* (list\* ’one ’two ’three ’four)) → \*some-list\* 
\*some-list\* → (ONE TWO THREE . FOUR)
(rplaca \*some-list\* ’uno)(UNO TWO THREE . FOUR)
\*some-list\* → (UNO TWO THREE . FOUR)
(rplacd (last \*some-list\*) (list ’IV))(THREE IV)
\*some-list\* → (UNO TWO THREE IV)

Side Effects:

The cons is modified.

Should signal an error of type type-error if cons is not a cons.

car, cdr, caar, cadr, cdar, cddr, caaar, caadr, cadar, . . .

Expanded Reference: rplaca, rplacd

Basic rplaca usage

rplaca destructively replaces the car of a cons cell. It returns the modified cons.

(let ((cell (cons 'a 'b)))
(rplaca cell 'x)
cell)
=> (X . B)

Basic rplacd usage

rplacd destructively replaces the cdr of a cons cell. It returns the modified cons.

(let ((cell (cons 'a 'b)))
(rplacd cell 'y)
cell)
=> (A . Y)

Modifying a list element

rplaca can change an element in a list by operating on the appropriate cons cell.

(let ((lst (list 1 2 3 4)))
(rplaca (cdr lst) 99) ; replace second element
lst)
=> (1 99 3 4)

Modifying list structure with rplacd

rplacd can truncate or extend a list by changing the cdr link.

;; Truncate a list after the second element
(let ((lst (list 'a 'b 'c 'd)))
(rplacd (cdr lst) nil)
lst)
=> (A B)

;; Splice another list in
(let ((lst (list 1 2 5))
(insert (list 3 4)))
(rplacd (cdr insert) (cddr lst))
(rplacd (cdr lst) insert)
lst)
=> (1 2 3 4 5)

Relationship to setf of car/cdr

rplaca and rplacd are equivalent to (setf (car cons) object) and (setf (cdr cons) object), except they return the cons rather than the new value.

(let ((cell (cons 'a 'b)))
(eq (rplaca cell 'x) cell))
=> T