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