
Tom's Lisp Function Definition
Lisp is fairly useless without the ability to define functions.
Now we have enough parts accumulated to attack that problem.
The most familiar form is to use
define:
(define (funcname parm1 . . . parmn) body)
This defines the funcname with the indicated parameter
names, parm1 through parmn.
The body is an arbitrary Tom's Lisp expression which
will be evaluated when the function is run. Parameter names
are set to the argument values before the expression is run.
lsp>(define (fred x) (+ (* 2 x) 1))
fred
lsp>(fred 3)
7
lsp>(fred 12)
25
lsp>(define (max x y) (if (< x y) y x))
max
lsp>(max 4 9)
9
lsp>(max 8 7)
8
lsp>(max 44 44)
44
lsp>(max 3 12)
12
Function definitions are usually placed in a file and loaded
into Tom's Lisp with the load command.
For instance, you can create the file fred.lsp:
; Get the second and third member of the list.
(define (nimrod lis)
(list (cadr lis) (caddr lis))
)
Then you can:
lsp>(load "fred.lsp")
nimrod
lsp>(nimrod '(a b c d e))
(b c)
lsp>(nimrod '(4 crud (t o m) 12))
(crud (t o m))
Non-trivial Lisp functions often employ recursion. That's how
things get done in Lisp. A standard example is the function to
compute the length of a list:
; Compute the length of a list.
(define (length lis)
(if (null? lis) 0
(+ 1 (length (cdr lis)))
)
)
So:
lsp>(length '(a b 12))
3
lsp>(length nil)
0
lsp>(length '((a b c) (d e f) g))
3
The length function says that if lis is empty, its length is
zero. Otherwise, its length is one plus the length of the remainder of
the list after removing the first item. Here are
some more examples..
Anonymous Functions
In Lisp, as in a few interpreted languages, anonymous
(nameless) functions can be created. Lisp does this with the
lambda operator. It takes the form
(lambda parameterlist body)
Here are some very complicated ways known add 5 and 8:
lsp>((lambda (x) (+ x 8)) 5)
13
lsp>((lambda (x y) (+ x y)) 8 5)
13
The expressions evaluated above are function calls. Instead of the name
of the function, we give the definition of the function.
We'll have more use for anonymous functions later.