Main Page | See live article | Alphabetical index

Closure (computer science)

In programming languages, a closure is an abstraction representing a function, plus the lexical environment (see static scoping) in which the function was created.

Closures are typically implemented with a special data structure that contains a pointer to the function code, plus a representation of the function's lexical environment (i.e., the set of available variables and their values) at the time when the closure was created.

Closures typically appear in languages that allow functions to be "first-class" values --- in other words, such languages allow functions to be passed as arguments, returned from function calls, bound to variable names, etc., just like simpler types such as strings and integers.

For example, in ML, the following code defines a function f that returns its argument plus 1:

fun f(x) = x + 1;
Such a function may "capture" name/value bindings from its enclosing environment, producing a closure. For example, in the code fragment:
val x = 1;
fun f(y) = x + y;
the closure data structure representing f contains a pointer to the enclosing environment, in which x is bound to 1. Therefore, f will always return its argument plus 1, even if the environment in which it is applied has a different value for x. Therefore, consider the code fragment:
let
  val x = 1;
  fun f(y) = x + y;
in
  let
    val x = 2;
  in
    f(3)
  end
end
In this code, the call f(3) occurs in an environment (the inner let) where x is bound to 2. However, the closure for f was constructed in an environment (the outer let) where x is bound to 1. Therefore the result of the call f(3) is 4, not 5.

Closures have many uses:

Note: Some speakers call any data structure that binds a lexical environment a closure, but the term usually refers specifically to functions.

Scheme was the first programming language to have fully general, lexically scoped closures. Virtually all functional programming languages, as well as the Smalltalk-descended object-oriented programming languages, support some form of closures. Some prominent languages that support closures include:

Some object-oriented languages enable the programmer to use objects to simulate some features of closures. For example: See also: