You can define a named function using the DEFUN
form:
(defun secret-number (the-number) (let ((the-secret 37)) (cond ((= the-number the-secret) 'that-is-the-secret-number) ((< the-number the-secret) 'too-low) ((> the-number the-secret) 'too-high)))) SECRET-NUMBER
We describedLET
,COND
, and'
(a.k.a.QUOTE)
in Lesson 3. The numeric comparison functions have the obvious meaning.
The DEFUN
form has three arguments:
SECRET-NUMBER
,(THE-NUMBER)
, which will be
bound to the function's parameters when it is called, and(LET ...)
.Since all three of these should stand for themselves,
DEFUN
does not evaluate any of its arguments. (If it did,
you'd face the inconvenience of having to quote each argument.)
DEFUN
returns the name of the defined function, and
installs a global definition using the name, parameter list, and body that
you supplied. Once you create a function using DEFUN
, you can
use it right away:
(secret-number 11) TOO-LOW (secret-number 99) TOO-HIGH (secret-number 37) THAT-IS-THE-SECRET-NUMBER
When you call the function, its parameter (e.g. 99
in the
second example) is bound to the argument name (i.e.
THE-NUMBER
) you supplied in the definition. Then, the body of
the function (i.e. (LET ...)
) is evaluated within the context
of the parameter binding. In other words, evaluating (SECRET-NUMBER
99)
causes the body of the SECRET-NUMBER
function
definition to be executed with the variable THE-NUMBER
bound
to 99
.
Of course, you can define a function of more than one argument:
(defun my-calculation (a b c x) (+ (* a (* x x)) (* b x) c)) MY-CALCULATION (my-calculation 3 2 7 5) 92
When calling a function, parameters are bound to argument names in order. Lisp has several optional variations on the list of argument names. Formally, this list is called a lambda list -- we'll examine some of its other features in Chapter 21.
At times you'll need a function in only one place in your program. You
could create a function with DEFUN
and call it just once.
Sometimes, this is the best thing to do, because you can give the function
a descriptive name that will help you read the program at some later
date. But sometimes the function you need is so trivial or so obvious
that you don't want to have to invent a name or worry about whether the
name might be in use somewhere else. For situations like this, Lisp lets
you create an unnamed, or anonymous, function using the
LAMBDA
form. A LAMBDA
form looks like a
DEFUN
form without the name:
(lambda (a b c x) (+ (* a (* x x)) (* b x) c))
You can't evaluate a LAMBDA
form; it must appear only where
Lisp expects to find a function -- normally as the first element of a
form:
(lambda (a b c x) (+ (* a (* x x)) (* b x) c)) Error ((lambda (a b c x) (+ (* a (* x x)) (* b x) c)) 3 2 7 5) 92