type: special form (fsubr) location: built-in source file: xlcont.c Common LISP compatible: yes supported on: all machines
(defun <symbol> <arg-list> <body> ) <symbol> - The name of the function being defined <arg-list> - A list of the formal arguments to the function of the form: ( [ <arg1> ... ] [ &optional <oarg1> ... ] [ &rest <rarg> ] [ &key ... ] [ &aux <aux1> ... ] ) <body> - A series of LISP forms (expressions) that are executed in order.
DEFUN defines a new function or re-defines an exisiting function. The last form in <body> that is evaluated is the value that is returned when the function is executed.
All of the <argN> formal arguments that are defined are required to appear in a call to the defined function. If there are any &OPTIONAL arguments defined, they will be filled in order. If there is a &REST argument defined, and all the required formal arguments and &OPTIONAL arguments are filled, any and all further parameters will be passed into the function via the <rarg> argument. Note that there can be only one <rarg> argument for &REST. If there are insufficient parameters for any of the &OPTIONAL or &REST arguments, they will contain NIL. The &AUX variables are a mechanism for you to define variables local to the function definition. At the end of the function execution, these local symbols and their values are are removed.
(defun my-add ; define function MY-ADD (num1 num2) ; with 2 formal parameters (+ num1 num2)) ; that adds the two paramters (my-add 1 2) ; returns 3 (defun foo ; define function FOO (a b &optional c d &rest e) ; with some of each argument (print a) (print b) ; (print c) (print d) ; print out each (print e)) ; (foo) ; error: too few arguments (foo 1) ; error: too few arguments (foo 1 2) ; prints 1 2 NIL NIL NIL (foo 1 2 3) ; prints 1 2 3 NIL NIL (foo 1 2 3 4) ; prints 1 2 3 4 NIL (foo 1 2 3 4 5) ; prints 1 2 3 4 (5) (foo 1 2 3 4 5 6 7 8 9) ; prints 1 2 3 4 (5 6 7 8 9) (defun my-add ; define function MY-ADD (num1 &rest num-list &aux sum) ; with 1 arg, rest, 1 aux var (setq sum num1) ; clear SUM (dotimes (i (length num-list) ) ; loop through rest list (setq sum (+ sum (car num-list))) ; add the number to sum (setq num-list (cdr num-list))) ; and remove num from list sum) ; return sum when finished (my-add 1 2 3 4) ; returns 10 (my-add 5 5 5 5 5) ; returns 25
COMMON LISP COMPATIBILITY: Common LISP supports an optional documentation string as the first form in the <body> of a DEFMACRO or DEFUN. XLISP will accept this string as a valid form, but it will not do anything special with it.