Node:setcdr, Next:, Previous:setcar, Up:car cdr & cons



7.6 setcdr

The setcdr function is similar to the setcar function, except that the function replaces the second and subsequent elements of a list rather than the first element.

To see how this works, set the value of the variable to a list of domesticated animals by evaluating the following expression:

(setq domesticated-animals '(horse cow sheep goat))

If you now evaluate the list, you will be returned the list (horse cow sheep goat):

domesticated-animals
     => (horse cow sheep goat)

Next, evaluate setcdr with two arguments, the name of the variable which has a list as its value, and the list to which the CDR of the first list will be set;

(setcdr domesticated-animals '(cat dog))

If you evaluate this expression, the list (cat dog) will appear in the echo area. This is the value returned by the function. The result we are interested in is the "side effect", which we can see by evaluating the variable domesticated-animals:

domesticated-animals
     => (horse cat dog)

Indeed, the list is changed from (horse cow sheep goat) to (horse cat dog). The CDR of the list is changed from (cow sheep goat) to (cat dog).