7.5 setcar

As you might guess from their names, the setcar and setcdr functions set the CAR or the CDR of a list to a new value. They actually change the original list, unlike car and cdr which leave the original list as it was. One way to find out how this works is to experiment. We will start with the setcar function.

First, we can make a list and then set the value of a variable to the list, using the setq special form. Because we intend to use setcar to change the list, this setq should not use the quoted form '(antelope giraffe lion tiger), as that would yield a list that is part of the program and bad things could happen if we tried to change part of the program while running it. Generally speaking an Emacs Lisp program’s components should be constant (or unchanged) while the program is running. So we instead construct an animal list by using the list function, as follows:

(setq animals (list 'antelope 'giraffe 'lion 'tiger))

If you are reading this in Info inside of GNU Emacs, you can evaluate this expression in the usual fashion, by positioning the cursor after the expression and typing C-x C-e. (I’m doing this right here as I write this. This is one of the advantages of having the interpreter built into the computing environment. Incidentally, when there is nothing on the line after the final parentheses, such as a comment, point can be on the next line. Thus, if your cursor is in the first column of the next line, you do not need to move it. Indeed, Emacs permits any amount of white space after the final parenthesis.)

When we evaluate the variable animals, we see that it is bound to the list (antelope giraffe lion tiger):

animals
     ⇒ (antelope giraffe lion tiger)

Put another way, the variable animals points to the list (antelope giraffe lion tiger).

Next, evaluate the function setcar while passing it two arguments, the variable animals and the quoted symbol hippopotamus; this is done by writing the three element list (setcar animals 'hippopotamus) and then evaluating it in the usual fashion:

(setcar animals 'hippopotamus)

After evaluating this expression, evaluate the variable animals again. You will see that the list of animals has changed:

animals
     ⇒ (hippopotamus giraffe lion tiger)

The first element on the list, antelope is replaced by hippopotamus.

So we can see that setcar did not add a new element to the list as cons would have; it replaced antelope with hippopotamus; it changed the list.