next up previous
Contents Next: do (SPECIAL FORM) Up: Appendix: Selected LISP Previous: cons (FUNTION)

defun (MACRO)

Format: (defun <name> (<par1> <par2> ... <parN>) <body>)

Required arguments: 2

<name>: a symbol which is appropriate as the name of funtion; (<par1> <par2> ...): a list of zero or more symbols which are appropriate as parameter names

Optional arguments: 1

<body>: a sequence of zero or more LISP expressions

The arguments to defun are not evaluated---they are used to establish a procedure definition. The first argument is a symbol which specifies the name of the function. This name can later be used to execute the <body> of the function. The parameter-list follows the name. This list specifies the number and order of arguments in a function call. Each <par> is symbol which may appear in the <body>. The value of each parameter, <par>, is determined by the value of corresponding argument in the function call. defun returns the name of the function.

Examples:

> (defun square (x)
     (* x x))
SQUARE

> (square 4)
16

> (square (+ 7 -2))
25

> (defun equal-length (lst1 lst2)
     (cond ((= (length lst1) (length lst2)) t)
           (t nil)))
EQUAL-LENGTH

> (equal-length '(a b c) '((d e) f g))
T

> (equal-length '() (rest '(a b)))
NIL

> (defun side-effect (x y)
     (setq x (* x x x))
     (+ x y))
SIDE-EFFECT

> (side-effect 2 3)
11

> (side-effect -4 14)
50



© Colin Allen & Maneesh Dhagat
November 1999