Next: , Previous: , Up: car cdr & cons   [Contents][Index]


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 to change the last element of a list, look ahead to The kill-new function, which uses the nthcdr and setcdr functions.)

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 (list '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).

This page has generated for branch:work/add_lispintr, commit:65845cf60c073f2f3182d1d07483530e9bbe1d96 to check Japanese translation.