# Anonymous functions

This may sound like a pointless idea: after all, if you can't name a function, you can't call it, nor can it be recursive. However, there are many situations when anonymous functions can be useful, although if you have not used a functional language before, it is less likely that you will have noticed their absence.

The notation for an anonymous function uses the special operator called `lambda` and looks like this:

`(lambda (` arg-1 ... arg-m`)` exp-1 ... exp-n`)`

`(lambda (` arg-1 ... arg-m `rest:` arg-m+1`)` exp-1 ... exp-n`)`

(Note: in Common Lisp, this form is prefixed by #'.) It can be used in the function position in a function application:

user> ((lambda (x) (* x x)) 3) 9 user> ((lambda (x . y) y) 1 2 3) (2 3) In the first example, the function `(lambda (x) ...)` is applied to the argument `3`. In the second the function `(lambda (x . y) ...)` is applied to the arguments `1`, `2` and `3`, the second and third of which become the elements of a list bound to `y`, which gives the result.

## Functional arguments

Anonymous functions can be passed as arguments to other functions, just like named functions. user> (defun foo (f x) (f x (+ 1 x))) foo user> (foo + 3) 7 user> (foo (lambda (a b) (* a b 2)) 3) 24 We begin this example by defining a function `foo`, which takes an argument `f` and an argument `x` and calls the function which is the value of `f` with the arguments `x` and `(+ x 1)`. Hence, if we call `foo` with `+` and `3` we obtain the result of `(+ 3 (+ 1 3))`. In the second case, `f` is a function of two arguments which computes the product of the two arguments and `2`.

## Functional results

A new concept, if you are coming from Pascal or C, is the creation of functional results, where anonymous functions are returned from function as results, for example: user> (defun add-n (n) (lambda (x) (+ x n))) add-n user> (setq z (add-n 3)) # user> (z 4) 7 What has happened is that the result of `add-n` is a function of one argument, in which the value of `n` is `3`, by virtue of the anonymous functional result being defined in the environment where `n` is associated with `3`. We can visualize this using the same technique as before: (setq z (add-n 3)) => (lambda (x) (+ x 3)) (z 4) => ((lambda (x) (+ x 3)) 4) => (+ 4 3) 7
Julian Padget, jap@maths.bath.ac.uk, this version December 9, 1994