Returning functions

In Lisp functions can return an object of any type, including another function. Here's an example of why this is useful.

Suppose we want to create a function to toggle an output line; for example, to turn an LED on or off. In our example a red LED is connected to D7, so we first need to make that an output:

(pinmode 7 t)

Now we could write a function red to toggle that LED:

(defun red () (digitalwrite 7 (not (digitalread 7))))

To turn on the LED we execute:

> (red)
t

If we have more than one LED we could write similar functions for the other LEDs, which would be quite repetitive if we have several LEDs. But Lisp can save us the trouble by allowing us to write a function mt (make-toggle) that returns a function to toggle a particular LED:

(defun mt (x) (lambda () (digitalwrite x (not (digitalread x)))

Now we can create a toggle function grn that toggles the green LED on pin D6:

(defvar grn (mt 6))

We can run this in the same way:

> (grn)

Note that the information about which output to use is stored inside the function grn in what's called a closure. Changing the value of x in the environment with a statement such as:

(defvar x 7)

doesn't affect the function grn.

uLisp prints the value of grn as:

<closure>

to indicate that it contains hidden information.