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
(define a-closure
(let ((x 10))
;; function created in environment where x = 10
(lambda (y)
(set! x (+ x y))
x)))
Emacs Lisp
;;; -*- lexical-binding: t; -*-
(defalias 'a-closure
(let ((x 10))
;; function created in environment where x = 10
(lambda (y)
(setq x (+ x y))
x)))
Javascript
{
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.