next up previous
Contents Next: Conditional Control Up: Defining LISP functions Previous: Using Your Own

Functions with Extended Bodies

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:

>(defun powers-of (x)
   (square x)
   (fourth-power x))

>(powers-of 2)
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.

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.

Powers-of does not have any side effects as it is, but change the definition as follows:

>(defun powers-of (x)
   (setq y (square x))
   (fourth-power x))
Watch what happens here:

>(powers-of 7)

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.

© Colin Allen & Maneesh Dhagat
November 1999