File: LISP-tutorial-16.html

package info (click to toggle)
cmucl 20c-2
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 42,524 kB
  • sloc: lisp: 358,331; ansic: 28,385; asm: 3,777; sh: 1,236; makefile: 366; csh: 31
file content (77 lines) | stat: -rw-r--r-- 2,105 bytes parent folder | download | duplicates (12)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<HTML>
<HEAD>
<TITLE>Common LISP Hints: Setf</TITLE>
</HEAD>
<BODY>
<A HREF="LISP-tutorial-15.html"><IMG SRC="prev.gif" ALT="Previous"></A>
<A HREF="LISP-tutorial-17.html"><IMG SRC="next.gif" ALT="Next"></A>
<A HREF="LISP-tutorial.html#toc16"><IMG SRC="toc.gif" ALT="Contents"></A>
<HR>
<H2><A NAME="s16">16. Setf</A></H2>

<P>Certain forms in LISP naturally define a memory location. For example,
if the value of <CODE>x</CODE> is a structure of type <CODE>foo</CODE>, then
<CODE>(foo-bar x)</CODE> defines 
the <CODE>bar</CODE> field of the value of <CODE>x</CODE>. Or, if the value of <CODE>y</CODE>
is a one-dimensional array, <CODE>(aref y 2)</CODE> defines the third element
of <CODE>y</CODE>. </P>
<P>The <CODE>setf</CODE> special form uses its first argument to define a place in
memory, evaluates its second argument, and stores the resulting value
in the resulting memory location. For example,</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
&gt; (setq a (make-array 3))
#(NIL NIL NIL)
&gt; (aref a 1)
NIL
&gt; (setf (aref a 1) 3)
3
&gt; a
#(NIL 3 NIL)
&gt; (aref a 1)
3
&gt; (defstruct foo bar)
FOO
&gt; (setq a (make-foo))
#s(FOO :BAR NIL)
&gt; (foo-bar a)
NIL
&gt; (setf (foo-bar a) 3)
3
&gt; a
#s(FOO :BAR 3)
&gt; (foo-bar a)
3
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P><CODE>Setf</CODE> is the only way to set the fields of a structure or the elements
of an array.</P>
<P>Here are some more examples of <CODE>setf</CODE> and related functions.</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
&gt; (setf a (make-array 1))       ;setf on a variable is equivalent to setq
#(NIL)
&gt; (push 5 (aref a 1))           ;push can act like setf
(5)
&gt; (pop (aref a 1))              ;so can pop
5
&gt; (setf (aref a 1) 5)
5
&gt; (incf (aref a 1))             ;incf reads from a place, increments,
6                               ;and writes back
&gt; (aref a 1)
6
</PRE>
</CODE></BLOCKQUOTE>
</P>


<HR>
<A HREF="LISP-tutorial-15.html"><IMG SRC="prev.gif" ALT="Previous"></A>
<A HREF="LISP-tutorial-17.html"><IMG SRC="next.gif" ALT="Next"></A>
<A HREF="LISP-tutorial.html#toc16"><IMG SRC="toc.gif" ALT="Contents"></A>
</BODY>
</HTML>