     Next: Anonymous Functions Up: Defining Your Own Previous: Defining Your Own

## Defining Functions

You can use the XLISP language to define functions of your own. Many of the functions you have been using so far are written in this language. The special form used for defining functions is called defun . The simplest form of the defun syntax is

```(defun fun args expression)
```
where fun is the symbol you want to use as the function name, args is the list of the symbols you want to use as arguments, and expression is the body of the function. Suppose for example that you want to define a function to delete a case from a list. This function should take as its arguments the list and the index of the case you want to delete. The body of the function can be based on either of the two approaches described in Section 4.3 above. Here is one approach:
```(defun delete-case (x i)
(select x (remove i (iseq 0 (- (length x) 1))) ) )
```
I have used the function length in this definition to determine the length of the argument x. Note that none of the arguments to defun are quoted: defun is a special form that does not evaluate its arguments.

Unless the functions you define are very simple you will probably want to define them in a file and load the file into XLISP-STAT with the load command. You can put the functions in the statinit.lsp file or include in statinit.lsp a load command that will load another file. The version of XLISP-STAT for the Macintosh includes a simple editor that can be used from within XLISP-STAT. The editor is described briefly in Section 5.6 above.

You can also write functions that send messages to objects. Here is a function that takes two regression models, assumed to be nested, and computes the F statistic for comparing these models:

```(defun f-statistic (m1 m2)
"Args: (m1 m2)
Computes the F statistic for testing model m1 within model m2."
(let ((send ss1 (m1 :sum-of-squares))
(send df1 (m1 :df))
(send ss2 (m2 :sum-of-squares))
(send df2 (m2 :df)))
(/ (/ (- ss1 ss2) (- df1 df2)) (/ ss2 df2))))
```
This definition uses the Lisp let   construct to establish some local variable bindings. The variables ss1, df1, ss2 and df2 are defined in terms of the two model arguments m1 and m2, and are then used to compute the F statistic. The string following the argument list is a documentation string. When a documentation string is present in a defun expression defun will install it so the help function will be able to retrieve it.     Next: Anonymous Functions Up: Defining Your Own Previous: Defining Your Own

Luke Tierney
Tue Jan 21 15:04:48 CST 1997