common-lisp Functions as first class values Closures


Example

Functions remember the lexical scope they where defined in. Because of this, we can enclose a lambda in a let to define closures.

(defvar *counter* (let ((count 0))
                    (lambda () (incf count))))

(funcall *counter*) ;; => 1
(funcall *counter*) ;; = 2

In the example above, the counter variable is only accessible to the anonymous function. This is more clearly seen in the following example

(defvar *counter-1* (make-counter))
(defvar *counter-2* (make-counter))

(funcall *counter-1*) ;; => 1
(funcall *counter-1*) ;; => 2
(funcall *counter-2*) ;; => 1
(funcall *counter-1*) ;; => 3