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
|
<HTML>
<HEAD>
<TITLE>Common LISP Hints: Structures</TITLE>
</HEAD>
<BODY>
<A HREF="LISP-tutorial-14.html"><IMG SRC="prev.gif" ALT="Previous"></A>
<A HREF="LISP-tutorial-16.html"><IMG SRC="next.gif" ALT="Next"></A>
<A HREF="LISP-tutorial.html#toc15"><IMG SRC="toc.gif" ALT="Contents"></A>
<HR>
<H2><A NAME="s15">15. Structures</A></H2>
<P>LISP structures are analogous to C structs or Pascal records. Here is
an example:</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
> (defstruct foo
bar
baaz
quux)
FOO
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P>This example defines a data type called <CODE>foo</CODE> which is a structure
containing 3 fields. It also defines 4 functions which operate on this
data type: <CODE>make-foo</CODE>, <CODE>foo-bar</CODE>, <CODE>foo-baaz</CODE>, and
<CODE>foo-quux</CODE>. The first one
makes a new object of type <CODE>foo</CODE>; the others access the fields of an
object of type <CODE>foo</CODE>. Here is how to use these functions:</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
> (make-foo)
#s(FOO :BAR NIL :BAAZ NIL :QUUX NIL)
> (make-foo :baaz 3)
#s(FOO :BAR NIL :BAAZ 3 :QUUX NIL)
> (foo-bar *)
NIL
> (foo-baaz **)
3
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P>The <CODE>make-foo</CODE> function can take a keyword argument for each of the
fields a structure of type <CODE>foo</CODE> can have. The field access functions
each take one argument, a structure of type <CODE>foo</CODE>, and return the
appropriate field.</P>
<P>See below for how to set the fields of a structure.</P>
<HR>
<A HREF="LISP-tutorial-14.html"><IMG SRC="prev.gif" ALT="Previous"></A>
<A HREF="LISP-tutorial-16.html"><IMG SRC="next.gif" ALT="Next"></A>
<A HREF="LISP-tutorial.html#toc15"><IMG SRC="toc.gif" ALT="Contents"></A>
</BODY>
</HTML>
|