emacs.d/clones/colinallen.dnsalias.org/lp/node71.html

80 lines
2.3 KiB
HTML

<!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN">
<!Originally converted to HTML using LaTeX2HTML 95 (Thu Jan 19 1995) by Nikos Drakos (nikos@cbl.leeds.ac.uk), CBLU, University of Leeds >
<HEAD>
<TITLE> Defmacro</TITLE>
</HEAD>
<BODY>
<meta name="description" value=" Defmacro">
<meta name="keywords" value="lp">
<meta name="resource-type" value="document">
<meta name="distribution" value="global">
<P>
<BR> <HR>
<A HREF="node72.html"><IMG ALIGN=BOTTOM ALT="next" SRC="next_motif.gif"></A>
<A HREF="node64.html"><IMG ALIGN=BOTTOM ALT="up" SRC="up_motif.gif"></A>
<A HREF="node70.html"><IMG ALIGN=BOTTOM ALT="previous" SRC="previous_motif.gif"></A> <BR>
<A HREF="lp.html"><B>Contents</B></A>
<B> Next:</B>
<A HREF="node72.html"> Appendix: Selected Lisp </A>
<B>Up:</B>
<A HREF="node64.html"> FunctionsLambda Expressions, </A>
<B> Previous:</B>
<A HREF="node70.html"> Backquote and Commas</A>
<BR> <HR> <P>
<H1> Defmacro</H1>
<P>
Macro definitions are similar to function definitions, but there are
some crucial differences. A macro is a piece of code that creates
another lisp object for evaluation. This process is called ``macro
expansion''. Macro expansion happens </em>before</em> any arguments
are evaluated.
<p>Here is an example of a macro definition:
<pre>
> (defmacro 2plus (x) (+ x 2))
2PLUS
> (2plus 3)
5
> (setf a (2plus 3)) ;; setf is a macro too!
5
</pre>
<p>
Because expansion occurs prior to evaluation, arguments passed to a
macro will not necessarily be evaluated. This result is that macros
behave rather differently from functions. For example:
<pre>
> (defmacro just-first-macro (x y) x)
JUST-FIRST-MACRO
> (just-first-macro 3 4)
3
> (just-first-macro 3 (print 4))
3 ;; (print 4) is <em>not</em> evaluated
> (defun just-first-function (x y) x)
JUST-FIRST-FUNCTION
> (just-first-function 3 (print 4))
4 ;; (print 4) <em>is</em> evaluated
3
</pre>
<p>
Many macros are built in to Lisp. For example (in addition to
<tt>setf</tt>) <tt>cond</tt>,
<tt>if</tt>, <tt>and</tt>, and <tt>or</tt> are all macros.
<p>
Macros are usually used to simplify or extend the syntax of the language.
Because macros do not evaluate all their arguments, they can sometimes result in
more efficient code.
<BR> <HR>
<P>
<ADDRESS>
<I>&#169; Colin Allen &amp; Maneesh Dhagat <BR>
May 1999</I>
</ADDRESS>
</BODY>