Go to the first, previous, next, last section, table of contents.


while

The while special form tests whether the value returned by evaluating its first argument is true or false. This is similar to what the Lisp interpreter does with an if; what the interpreter does next, however, is different.

In a while expression, if the value returned by evaluating the first argument is false, the Lisp interpreter skips the rest of the expression (the body of the expression) and does not evaluate it. However, if the value is true, the Lisp interpreter evaluates the body of the expression and then again tests whether the first argument to while is true or false. If the value returned by evaluating the first argument is again true, the Lisp interpreter again evaluates the body of the expression.

The template for a while expression looks like this:

(while true-or-false-test
  body...)

So long as the true-or-false-test of the while expression returns a true value when it is evaluated, the body is repeatedly evaluated. This process is called a loop since the Lisp interpreter repeats the same thing again and again, like an airplane doing a loop. When the result of evaluating the true-or-false-test is false, the Lisp interpreter does not evaluate the rest of the while expression and `exits the loop'.

Clearly, if the value returned by evaluating the first argument to while is always true, the body following will be evaluated again and again ... and again ... forever. Conversely, if the value returned is never true, the expressions in the body will never be evaluated. The craft of writing a while loop consists of choosing a mechanism such that the true-or-false-test returns true just the number of times that you want the subsequent expressions to be evaluated, and then have the test return false.

The value returned by evaluating a while is the value of the true-or-false-test. An interesting consequence of this is that a while loop that evaluates without error will return nil or false regardless of whether it has looped 1 or 100 times or none at all. A while expression that evaluates successfully never returns a true value! What this means is that while is always evaluated for its side effects, which is to say, the consequences of evaluating the expressions within the body of the while loop. This makes sense. It is not the mere act of looping that is desired, but the consequences of what happens when the expressions in the loop are repeatedly evaluated.


Go to the first, previous, next, last section, table of contents.