My attempt at explaining closures

2019/05/15

C: Trying To Explain

A closure is a function associated with a local, persistent, environment. It is a language feature — some languages attach local environments to functions, some languages don’t.

This lets functions keep a persistent state without using global variables.

To define a function that has persistent local variables in a language that supports this, create it in a local environment where you’d define these local variables. In Lisp family languages, this means a lambda wrapped inside a let: the local binding of that let will become part of the lambda’s environment.

Scheme:

1
2
3
4
5
6
(define a-closure
  (let ((x 10))
    ;; function created in environment where x = 10
    (lambda (y)
      (set! x (+ x y))
      x)))

Emacs Lisp:

1
2
3
4
5
6
7
;;; -*- lexical-binding: t; -*-
(defalias 'a-closure
  (let ((x 10))
    ;; function created in environment where x = 10
    (lambda (y)
      (setq x (+ x y))
      x)))

JavaScript:

1
2
3
4
5
6
7
8
{
  let x = 10;
  // function created in environment where x = 10
  function a_closure(y) {
    x += y;
    return x;
  }
}

As far as a_closure is concerned, x might as well be a global variable. It is a persistent variable outside of the function that happens to only be accessible to the function.