next up previous
Next: 3.2 Logical Connectives Up: 3. EXTENSION OF THE Previous: 3. EXTENSION OF THE

3.1 Functional Arguments

Mathematically, it is possible to have functions as arguments of other functions. For example, in arithmetic one could define a function operate[op,a,b], where op is a functional argument that specifies which arithmetic operation is to be performed on a and b. Thus

        operate[+;3;4]=7    and 
        operate[*;3;4]=12

In LISP, functional arguments are extremely useful. A very important function with a functional argument is maplist. Its M-expression definition is

maplist[x;fn]=[null[x] $\rightarrow$NIL; 
        T $\rightarrow$cons[fn[x];maplist[cdr[x];fn]]]

An examination of the universal function evalquote will show that the interpreter can handle maplist and other functions written in this manner without any further addition. The functional argument is, of course, a function translated into an S-expression. It is bound to the variable fn and is then used whenever fn is mentioned as a function. The S-expression for maplist itself is as follows:

(MAPLIST (LAMBDA (X FN) (COND ((NULL X) NIL) 
(T (CONS (FN X) (MAPLIST (CDR X) FN))) )))

Now suppose we wish to define a function that takes a list and changes it by cons-ing an X onto every item of the list so that, for example,

change[(A B (C D))]=((A . X) (B . X) ((C . D) . X))

Using maplist, we define change by

change[a]=maplist[a; $\lambda$[[j];cons[car[j];X]]]

This is not a valid M-expression as defined syntactically in section 1.5 because a function appears where a form is expected. This can be corrected by modifying the rule defining an argument so as to include functional arguments:

         $<$argument $> ::= <$form $> \vert <$function $>$

We also need a special rule to translate functional arguments into S-expression. If fn is a function used as an argument, then it is translated into (FUNCTION $fn^{*}$).

Example

(CHANGE (LAMBDA (A) (MAPLIST A (FUNCTION 
        (LAMBDA (J) (CONS (CAR J) (QUOTE X))) )))

An examination of evalquote shows that QUOTE will work instead of FUNCTION, provided that there are no free variables present. An explanation of how the interpreter processes the atomic symbol FUNCTION is given in the Appendix B.


next up previous
Next: 3.2 Logical Connectives Up: 3. EXTENSION OF THE Previous: 3. EXTENSION OF THE