emacs.d/clones/lisp/colinallen.dnsalias.org/lp/node35.html

68 lines
2.9 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> Local Variables Using Let</TITLE>
</HEAD>
<BODY>
<meta name="description" value=" Local Variables Using Let">
<meta name="keywords" value="lp">
<meta name="resource-type" value="document">
<meta name="distribution" value="global">
<P>
<BR> <HR>
<A HREF="node36.html"><IMG ALIGN=BOTTOM ALT="next" SRC="next_motif.gif"></A>
<A HREF="node29.html"><IMG ALIGN=BOTTOM ALT="up" SRC="up_motif.gif"></A>
<A HREF="node34.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="node36.html"> Iteration Using Dolist</A>
<B>Up:</B>
<A HREF="node29.html"> Recursion and Iteration</A>
<B> Previous:</B>
<A HREF="node34.html"> Iteration Using Dotimes</A>
<BR> <HR> <P>
<H1> Local Variables Using Let</H1>
<P>
The general form of a let statement is:
<BLOCKQUOTE>
<PRE> (let ((&lt;vbl1&gt; &lt;expr1&gt; )
...............
(&lt;vbln&gt; &lt;exprn&gt; ))
&lt;body&gt; )
</PRE>
</BLOCKQUOTE>
The first part of a let statement is a list of pairs of variable names and expressions providing initial values for those variables. If any of the value expressions is omitted, the corresponding variable is set initially to nil. The left parenthesis before let matches the right parenthesis after the body, and together they define the code block within which the local variables are recognized. The body, as usual, is any sequence of Lisp expressions. Let returns the value of the last expression evaluated in the body.
<P>
Here is an example of a let statement evaluated directly by the interpreter:
<BLOCKQUOTE>
<PRE>&gt; (let ((this 3)
(that (- 67 34)))
(* this that))
99
</PRE>
</BLOCKQUOTE>
Sometimes when setting up a lot of local variables one would like the value of one variable to depend on another. Let, however, does all its assignments in parallel, so that, for instance:
<BLOCKQUOTE>
<PRE>(let ((this 3)
(that this))
(* this that))
</PRE>
</BLOCKQUOTE>
produces an error since <tt>this</tt> is still an unbound variable when the let statement tries to assign the value of <tt>that</tt>. Let has a sibling let* which does its variable assignments sequentially. So:
<BLOCKQUOTE>
<PRE>(let* ((this 3)
(that this))
(* this that))
</PRE>
</BLOCKQUOTE>
is fine, and intializes both <tt>this</tt> and <tt>that</tt> to the value 3.
<P>
Let has applications beyond iterative processes. Anytime you need a temporary storage handle for a value, good Lisp programming demands that you should think in terms of using a let statement rather than a global variable.
<P>
<BR> <HR>
<P>
<ADDRESS>
<I>&#169; Colin Allen &amp; Maneesh Dhagat <BR>
February 2007</I>
</ADDRESS>
</BODY>