next up previous
Contents Next: Iteration Using Dolist Up: Recursion and Iteration Previous: Iteration Using Dotimes

Local Variables Using Let

The general form of a let statement is:

        (let ((<vbl1>  <expr1> )
               ...............
              (<vbln>  <exprn> ))
             <body> )
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.

Here is an example of a let statement evaluated directly by the interpreter:

> (let ((this 3)
       (that (- 67 34)))
   (* this that))
99
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:
(let ((this 3)
      (that this))
   (* this that))
produces an error since this is still an unbound variable when the let statement tries to assign the value of that. Let has a sibling let* which does its variable assignments sequentially. So:
(let* ((this 3)
       (that this))
   (* this that))
is fine, and intializes both this and that to the value 3.

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.



© Colin Allen & Maneesh Dhagat
February 2007