Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Functions and Closures

Closures and Lexical Scope

Learn how Common Lisp closures capture lexical variables to keep private state: counters, accumulators, shared state between functions, memoization and loop-variable pitfalls.

A closure is a function together with the lexical variables it can see. When a function is created inside a let or another function, it remembers those variables even after the code that made them has finished. Closures give you private, persistent state without classes or global variables, and they are the engine behind callbacks, iterators, memoization and many macro-generated helpers. This lesson shows how closures work and how to use them well.

Lexical scope, once more

A variable bound by let or by function parameters is lexical: it is visible only in the code written inside that form. But a lambda written inside that form can capture it.

LISP
(defun make-adder (n)
  (lambda (x) (+ x n)))      ; the lambda captures N

(defparameter *add5* (make-adder 5))
(defparameter *add10* (make-adder 10))

(funcall *add5* 1)      ; => 6
(funcall *add10* 1)     ; => 11

make-adder has returned by the time you call *add5*, yet the 5 is still there. Each call to make-adder creates a fresh binding of n, so *add5* and *add10* do not interfere.

A counter with private state

Closures can modify captured variables, not just read them:

LISP
(defun make-counter ()
  (let ((count 0))
    (lambda ()
      (incf count))))

(defparameter *a* (make-counter))
(defparameter *b* (make-counter))

(funcall *a*)   ; => 1
(funcall *a*)   ; => 2
(funcall *a*)   ; => 3
(funcall *b*)   ; => 1     b has its own count

The variable count is reachable only through the function. No other code can read or change it, which makes it private.

The Mini-Lisp below (a JavaScript stand-in interpreter, not SBCL) runs the same code, with setf instead of incf, which Mini-Lisp lacks:

JS Mini-Lisp: counters and adders

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Several functions sharing one variable

Return more than one function from the same let, and they share the captured variable. This is "let over lambda":

LISP
(defun make-account (balance)
  (list
   :deposit  (lambda (amount) (incf balance amount))
   :withdraw (lambda (amount)
               (if (> amount balance)
                   (error "Insufficient funds")
                   (decf balance amount)))
   :balance  (lambda () balance)))

(defparameter *acct* (make-account 100))
(funcall (getf *acct* :deposit) 50)      ; => 150
(funcall (getf *acct* :withdraw) 30)     ; => 120
(funcall (getf *acct* :balance))         ; => 120

The three lambdas close over the same balance. Nothing outside can touch it directly. This is the object-oriented idea of encapsulation, built from nothing but lambdas.

Global functions with private state

A defun placed inside a let at top level also closes over the variable:

LISP
(let ((next-id 0))
  (defun new-id ()
    (incf next-id)))

(new-id)   ; => 1
(new-id)   ; => 2

This is a common idiom for a counter or cache that must not be a global variable.

Closures capture variables, not values

The closure captures the binding, so later changes are visible:

LISP
(let* ((x 1)
       (show (lambda () x)))
  (setf x 2)
  (funcall show))        ; => 2   not 1

This is the root of the classic loop pitfall. Suppose you want a list of functions, one per loop iteration:

LISP
(let ((fns '()))
  (do ((i 0 (1+ i)))
      ((= i 3))
    (push (lambda () i) fns))
  (mapcar #'funcall (nreverse fns)))
;; => (3 3 3)   because `do` reuses ONE binding of i that ends at 3

The standard allows do to update a single binding (and says dotimes may do either), so you cannot rely on a fresh i per iteration. The fix is to make a new binding explicitly:

LISP
(let ((fns '()))
  (do ((i 0 (1+ i)))
      ((= i 3))
    (let ((j i))                          ; fresh variable each iteration
      (push (lambda () j) fns)))
  (mapcar #'funcall (nreverse fns)))
;; => (0 1 2)

Remember this rule: if each closure needs its own value, bind a new variable inside the loop body. The stand-in below reproduces the effect in JavaScript, where var has the one-binding behavior of do and let gives a fresh binding.

JS Stand-in: shared vs fresh bindings

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Memoization

A closure over a hash table can cache results of an expensive function:

LISP
(defun memoize (fn)
  (let ((cache (make-hash-table :test 'equal)))
    (lambda (&rest args)
      (multiple-value-bind (value found) (gethash args cache)
        (if found
            value
            (setf (gethash args cache) (apply fn args)))))))

(defun slow-square (x)
  (sleep 1)
  (* x x))

(defparameter *fast-square* (memoize #'slow-square))
(funcall *fast-square* 12)   ; takes a second
(funcall *fast-square* 12)   ; instant: cached

The cache lives in the closure and nowhere else. Keys are the argument lists, so the table uses equal.

Iterators and generators

Closures make tiny iterators:

LISP
(defun make-iterator (list)
  (lambda ()
    (if list
        (values (pop list) t)
        (values nil nil))))

(let ((next (make-iterator '(a b c))))
  (list (funcall next) (funcall next) (funcall next)))
;; => (A B C)

The list parameter is captured and shrinks each time. Another call to make-iterator starts a new, independent walk.

Closures and dynamic variables

Closures capture lexical variables only. Special variables (defvar, defparameter) are looked up when the code runs, so a closure sees whatever dynamic binding is active at call time, not creation time. Use lexical variables for state you want to keep with the function, and special variables for configuration that flows through calls (Symbols, Variables and Scope).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a closure remember?

    A closure keeps the bindings of the lexical variables it uses alive, so later changes are visible.
  2. 2. Two counters made by make-counter share a count. True or false?

    The let inside make-counter runs on every call, creating a new count each time.
  3. 3. Why might (do ((i 0 (1+ i))) ((= i 3)) (push (lambda () i) fns)) give (3 3 3)?

    All the lambdas captured the same binding; bind a fresh variable inside the body to avoid it.
  4. 4. Which idiom gives a global function private state?

    defun inside a let creates a closure over the let variable.
  5. 5. What kind of variable does a closure capture?

    Lexical variables are captured; special variables are looked up dynamically at call time.

Summary

  • A closure is a function plus the lexical bindings it references; those bindings outlive the form that created them.
  • (let ((count 0)) (lambda () (incf count))) gives a function with private, mutable state.
  • Functions created in the same let share its variables.
  • Closures capture variables, not values; bind a fresh variable in a loop body when each closure needs its own.
  • Closures power memoization, iterators and encapsulation.

Next: Recursion and Tail Calls