next up previous
Contents Next: symbolp (PREDICATE) Up: Appendix: Selected Lisp Previous: secondthird, etc.

setf (MACRO)

Format:

(setf <place1>  <val1> 
      <place2>  <val2> 
      .
      .
      <placeN>  <valN> )

Required arguments: none

Optional arguments: any even number of arguments

<place> : either (i) the name of a variable, or (ii) an expression referring to part of a larger structure (e.g. a list, property list, structure, or array). <val> : any Lisp expression.

setf assigns the result of evaluating <val> to the location specified in the immediately preceding <place> . It returns the result of evaluating the last <val> . If no <place> -<val> pairs are specified, setf returns nil. setf is used, among other things, to assign values to variables, change parts of list structures, and to manage property lists and structures. Examples of all these uses are given in the chapters of this book. Other uses, too numerous to document here, can be found in Steele.

Examples: (see all chapters for further examples)

> (setf crew '(picard riker worf crusher))
(PICARD RIKER WORF CRUSHER)

> (setf (first crew)  (list 'captain (first crew))
       (second crew) (list 'commander (second crew))
       (third crew)  (list 'lieutenant (third crew))
       (fourth crew) (list 'ensign (fourth crew)))
(ENSIGN CRUSHER)

> crew
((CAPTAIN PICARD) (COMMANDER RIKER) (LIEUTENANT WORF)
 (ENSIGN CRUSHER))

> (setf (get 'picard 'rank) 'captain)
CAPTAIN

> (get 'picard 'rank)
CAPTAIN

> (defstruct starship crew captain)
STARSHIP

> (setf enterprise (make-starship))
#S(STARSHIP CREW NIL CAPTAIN NIL)

> (setf (starship-crew enterprise)    (rest crew)
       (starship-captain enterprise) (second (first crew)))
PICARD

> enterprise
#S(STARSHIP CREW
      ((COMMANDER RIKER) (LIEUTENANT WORF) (ENSIGN CRUSHER))
      CAPTAIN PICARD)



© Colin Allen & Maneesh Dhagat
March 2007