http://en.wikipedia.org/wiki/Closure_(computer_science)
first-class Function + Free variables (upvalues)
In computer science, a closure is a first-class function with free variables that are bound in the lexical environment.
Such a function is said to be "closed over" its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself.
In some languages, a closure may occur when a function is defined within another function, and the inner function refers to local variables of the outer function. At runtime, when the outer function executes, a closure is formed, consisting of the inner function’s code and references to any variables of the outer function required by the closure; such variables are called theupvalues of the closure.
The term closure is often mistakenly used to mean anonymous function. This is probably because most languages implementing anonymous functions allow them to form closures and programmers are usually introduced to both concepts at the same time. These are, however, distinct concepts.
C++
C++ allows defining function objects by overloading operator()
. These objects behave somewhat like functions in a functional programming language. They may be created at runtime and may contain state, but they do not implicitly capture local variables as closures do. Two proposals to introduce C++ language support for closures (both proposals call them lambda functions) are being considered by the C++ Standards Committee [1], [2]. The main difference between these proposals is that one stores a copy of all the local variables in a closure by default, and another stores references to original variables. Both provide functionality to override the default behaviour. If some form of these proposals is accepted, one would be able to write
Python
Python provides a keyword lambda
which creates a closure. Python's lambda
is restricted to a single expression, and can contain no statements. For a more comprehensive closure a custom function or inline class can be written.
Java
Java allows defining "anonymous classes" inside a method; an anonymous class may refer to names in lexically enclosing classes, or read-only variables (marked as final) in the lexically enclosing method.
Java also supports another form of classes, which are called inner (or nested) classes.[10] [11] These are defined in the body of an enclosing class and have full access to each and every instance variable of the enclosing class, thus resembling standard function closures
According to a Java 7 proposal[9], closures will allow the above code to be executed as
Conclusion:
A language support first-class function is naturally has function object.
Closure is a special first-class function which bound with free variables (E.g, local variable of Outer function)