Opentopia Directory Encyclopedia Tools

Closure (computer science)

Encyclopedia : C : CL : CLO : Closure (computer science)



 

In programming languages, a closure is a function that refers to free variables in its lexical context.

A closure typically comes about when one function is declared entirely within the body of another, and the inner function refers to local variables of the outer function. At run time, when the outer function executes, a closure is formed. It consists of the function code, and references to any variables in the outer function's scope that the closure needs.

Closures are commonly used in functional programming to defer calculation, to hide state, and as arguments to higher-order functions.

A closure combines the code of a function with a special lexical environment bound to that function (scope). Closure lexical variables differ from global variables in that they do not occupy the global variable namespace. They differ from object oriented member variables in that they are bound to function invocations, not object instances.

Implementation and theory

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 function was created.

Closures are closely related to Actors in the Actor model of concurrent computation where the values in the function's lexical environment are called acquaintances. An important issue for closures in concurrent programming languages is whether the variables in a closure can be updated and if so how these updates can be synchronized. Actors provide one solution (Will Clinger 1981).

Examples

Closures typically appear in languages in which functions are 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, consider the following Lisp function:

(defun best-selling-books (threshold)
"Return a list of all books with at least THRESHOLD copies sold."
(filter
#'(lambda (book) (>= (book-sales book) threshold))
*book-list*))
Here the lambda expression (lambda (book) (>= (book-sales book) threshold)) appears within the function best-selling-books. When the lambda expression is evaluated, Lisp creates a closure consisting of the code for the lambda and a reference to the threshold variable, which the lambda uses.

The closure is then passed to the filter function, which calls it repeatedly to determine which books are to be added to the result list and which are to be discarded. Because the closure itself has a reference to threshold, it can use that variable each time filter calls it. filter might be defined in a completely separate file.

A function may create a closure and return it. The following example is a function that returns a function.

(defun derivative (f dx)
"Return a function that approximates the derivative of f
using an interval of dx, which should be appropriately small."
#'(lambda (x) (/ (- (funcall f (+ x dx)) (funcall f x))
dx)))
Because the closure in this case outlives the scope of the function that creates it, the variables f and dx live on after the function derivative returns. In languages without closures, the lifetime of a local variable coincides with the execution of the scope where that variable is declared. In languages with closures, variables continue to exist as long as any existing closures have references to them.

Uses of closures

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.

Programming languages with closures

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.

Eiffel has a notion of agent. An agent is an object wrapping a routine, with some arguments possibly evaluated ("closed") and others left for evaluation at the time of call ("open"). Eiffel agents are extensively used in GUI programming, numerical applications, database manipulation, and reflection.

Though semantics vary greatly, many modern, general-purpose programming languages have lexical scoping and some variation on closures.

Closure-like constructs in other languages

In C, libraries that support callbacks sometimes allow a callback to be registered using two values: a function pointer and a separate void * pointer to arbitrary data of the user's choice. Each time the library executes the callback function, it passes in the data pointer. This allows the callback to maintain state and to refer to information captured at the time it was registered. The idiom is similar to closures in functionality, but not in syntax.

Several object-oriented techniques and language features simulate some features of closures. For example:

void foo(string myname) );
// i is now either n.end() or points to the first string in n
// which is not equal to  myname and which length is greater than y
}

class CalculationWindow extends JFrame " is an anonymous class. Runnable runner = new Runnable() }; new Thread(runner).start(); } }

Implementation

A language implementation cannot easily support full closures if its run-time memory model allocates all local variables on a linear stack. In such languages, a function's local variables are deallocated when the function returns. However, a closure requires that the free variables it references survive the enclosing function's execution. Therefore those variables must be allocated so that they persist until no longer needed. This explains why typically languages that natively support closures use garbage collection.

A typical modern Scheme implementation allocates local variables that might be used by closures dynamically and stores all other local variables on the stack.

See also

Reference

External links

 


From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.


Search Titles
0123456789
ABCDEFGHIJ
KLMNOPQRST
UVWXYZ?

E-mail this article to:

Personal Message: