Previous Next Contents

21. Lambda

If you just want to create a temporary function and don't want to bother giving it a name, lambda is what you need.

> #'(lambda (x) (+ x 3))
(LAMBDA (X) (+ X 3))
> (funcall * 5)               ;* is the last result,remember?
8
<tscreen><verb>

The combination of <tt/lambda/ and <tt/mapcar/ can replace many loops. For
example, the following two forms are equivalent:

<tscreen><verb>
> (do ((x '(1 2 3 4 5) (cdr x))
       (y nil))
      ((null x) (reverse y))
    (push (+ (car x) 2) y))
(3 4 5 6 7)
> (mapcar #'(lambda (x) (+ x 2)) '(1 2 3 4 5))
(3 4 5 6 7)

However the first version will run significantly faster when compiled by CMUCL. But speed isn't everything and the second version is a lot clearer and easier to debug.


Previous Next Contents