next up previous
Contents Next: Exercises Up: LISt Processing Previous: More Functions and

Setf

Setq is useful for changing the values of variables. For example:

>(setq my-age (+ my-age 1))
11
>(setq a (cdr a))
(a s d f)
LISP programs very frequently make use of changes of this sort. But sometimes one would like to change just part of the value of a variable. Suppose you assign a value to a variable as follows:
>(setq words '(a list of words))
(A LIST OF WORDS)
What if you want to change just part of the list that is the value of words? Well, you could say
>(setq words (cons 'this (rest words)))
(THIS LIST OF WORDS)
but with lengthy list structures this can get complicated. What you need is a way to change just part of a list; setf is what you need. Look at this sequence to see just some of the ways in which it can be used.
>(setf (first words) 'the)
THE
>words
(THE LIST OF WORDS)
>(setf (third words) 'is)
IS
>words
(THE LIST IS WORDS)
>(setf (rest words) '(game is up))
(GAME IS UP)
>words
(THE GAME IS UP)
Now you know enough to do the exercises below.



© Colin Allen & Maneesh Dhagat
November 1999