70 lines
2.4 KiB
HTML
70 lines
2.4 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> Functions with Extended Bodies</TITLE>
|
||
|
</HEAD>
|
||
|
<BODY>
|
||
|
<meta name="description" value=" Functions with Extended Bodies">
|
||
|
<meta name="keywords" value="lp">
|
||
|
<meta name="resource-type" value="document">
|
||
|
<meta name="distribution" value="global">
|
||
|
<P>
|
||
|
<BR> <HR>
|
||
|
<A HREF="node21.html"><IMG ALIGN=BOTTOM ALT="next" SRC="next_motif.gif"></A>
|
||
|
<A HREF="node15.html"><IMG ALIGN=BOTTOM ALT="up" SRC="up_motif.gif"></A>
|
||
|
<A HREF="node19.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="node21.html"> Conditional Control</A>
|
||
|
<B>Up:</B>
|
||
|
<A HREF="node15.html"> Defining Lisp functions</A>
|
||
|
<B> Previous:</B>
|
||
|
<A HREF="node19.html"> Using Your Own </A>
|
||
|
<BR> <HR> <P>
|
||
|
<H1> Functions with Extended Bodies</H1>
|
||
|
<P>
|
||
|
As mentioned before, a function definition may contain an indefinite number of expressions in its body, one after the other. Take the following definition, which has two:
|
||
|
<BLOCKQUOTE>
|
||
|
<PRE>> (defun powers-of (x)
|
||
|
(square x)
|
||
|
(fourth-power x))
|
||
|
POWERS-OF
|
||
|
|
||
|
> (powers-of 2)
|
||
|
16
|
||
|
</PRE>
|
||
|
</BLOCKQUOTE>
|
||
|
Notice that this function only returns the value of the last expression in its body. In this case the last expression in the body is (fourth-power x) so only the value 16 gets printed in the example above.
|
||
|
<P>
|
||
|
What is the point of having more than one expression in the body of a function if it only ever returns the last? The answer to this question is that we may be interested in side effects of the intermediate evaluations.
|
||
|
<P>
|
||
|
Powers-of does not have any side effects as it is, but change the definition as follows:
|
||
|
<BLOCKQUOTE>
|
||
|
<PRE>> (defun powers-of (x)
|
||
|
(setq y (square x))
|
||
|
(fourth-power x))
|
||
|
POWERS-OF
|
||
|
</PRE>
|
||
|
</BLOCKQUOTE>
|
||
|
Watch what happens here:
|
||
|
<BLOCKQUOTE>
|
||
|
<PRE>> y
|
||
|
27
|
||
|
|
||
|
> (powers-of 7)
|
||
|
2401
|
||
|
|
||
|
> y
|
||
|
49
|
||
|
</PRE>
|
||
|
</BLOCKQUOTE>
|
||
|
The side effect of powers-of was to set the value of the variable y to 49. Since y did not appear in the parameter list of powers-of, it is treated as a global variable, and the effect of the set lasts beyond the life of your call to powers-of.
|
||
|
<P>
|
||
|
<BR> <HR>
|
||
|
<P>
|
||
|
<ADDRESS>
|
||
|
<I>© Colin Allen & Maneesh Dhagat <BR>
|
||
|
March 2007 </I>
|
||
|
</ADDRESS>
|
||
|
</BODY>
|