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:

  • Designers of software libraries can allow users to customize behavior by passing closures as arguments to important functions. For example, a function that sortss values can accept a closure argument that compares the values to be sorted according to a user-defined criterion.
  • Because closures delay evaluation --- i.e., they do not "do" anything until they are called --- they can be used to define control structures. For example, all Smalltalk's standard control structures, including branches (if/then/else) and loops (while and for), are defined using objects whose methods accept closures. Users can easily define their own control structures as well.
  • Multiple functions can be produced which close over the same environment, enabling them to communicate privately by altering that environment.

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:
  • Java allows the programmer to define "anonymous classeses" inside a method; an anonymous class may refer to names in lexically enclosing classes, or immutable names in the lexically enclosing method.
  • In C++, programmers may define classes that overload the () (function application) operator. This enables instances of this class to behave syntactically like closures, although C++ provides no direct support for capturing names in the enclosing function's environment (the programmer can simulate some aspects of environment capture by using data members in the class). Instances of such classes are called function objects, or occasionally functors (although the latter term is confusing, because it has a very different meaning in other programming languages).

See also:
  • funarg problem


In the News

[Ironic] Professional beggars prowling about the streets of Moroccan c
The government plans to crack down on the scam used by faux beggars in growing numbers for a kind of "emotional blackmail", a cabinet minister was quoted as saying...

Tempting Fate
Series of articles from October and November 2005 that conclude that there is "no major city in America more at risk of a catastrophic New Orleans-style flood than Sacramento,"California. Topics include the levees in Sacramento, safety issues with Folsom Dam, flood-prone areas of the Sacramento-San Joaquin River Delta area, legislation and government policy, and more. Includes graphics, photos (requires free registration), and archived articles. From the Sacramento Bee.

Superconducting Turbojet
An all-electric aircraft could soon appear over the horizon. The new type of aircraft, currently on the drawing board, could be far more efficient than conventional aircraft, produce less greenhouse emissions, and be quieter. Air travel is on the increase, but it comes at a price in terms of the emissions driving climate change. Aircraft currently account for about 5% of UK emissions with a single long-haul flight the equivalent of a ton of carbon dioxide per passenger.

Male pill
Despite Carl Djerassi’s prediction (some years ago) that we would never see a “male pill”, it looks like just such a contraceptive treat is coming at last.The new drug, Adjudin, is currently in early clinical trials and is a long way from human use. However, the very fact that drug companies are taking a male [...]

Sex and phthalates
It seems even the sex industry is not immune to chemophobia, according to a recent Greenpeace Netherlands announcement, users of PVC sex toys destined for orificial use should not. Use them, that is.According to Greenpeace, these plastic devices can contain “extremely high concentrations of phthalate plasticisers which allegedly pose a risk to human health and [...]

World Drug Report
A publication about worldwide illegal drug production, trafficking, and use. Find data and analysis on opium, heroin, cocaine, cannabis, amphetamine-type stimulants, and other drugs. The 2006 report features a special section on cannabis, "by far the most widely produced, trafficked and used drug in the world."Includes archived reports from past years. Some material available in additional languages. From the United Nations Office on Drugs and Crime (UNODC).

Green Tea Extract Shows Potential As An Anti-cancer Agent
A study on bladder cancer cell lines showed that green tea extract has potential as an anti-cancer agent, proving for the first time that it is able to target cancer cells while leaving healthy cells alone.

Shadowy face recognition
Face recognition is the most obvious approach to identification but it suffers from a major drawback - shadows and bad lighting. If there is inconsistent lighting in a room or on a face then it becomes difficult to produce reproducible digital image of the face for face recognition algorithms to work with. Now, researchers in [...]

Proposed Global Warming Solution Needs More Scientific Research
Neither the safety nor the effectiveness of ocean fertilization -- adding iron or other 'micronutrients'to the sea to encourage plankton to grow -- have been established and the method should not be touted as a cure for climate change until they have been, cautions the World Conservation Union. The idea behind the method is that micronutrients such as iron or urea will stimulate the growth of phytoplankton in the sea, which can absorb large quantities of carbon dioxide from the atmosphere.

Rolls-Royce Acquires License To Use Iowa State Discovery That Improves
Rolls-Royce Corp. has acquired exclusive rights to use a coating invented by Iowa State University researchers that helps turbines stand up to the heat in jet engines. The unique bond coating will be applied to engine turbine blades made of nickel-based superalloys. Those superalloys are designed for strength but need help withstanding metal temperatures approaching 2,100 degrees Fahrenheit inside the hot section of a jet engine.


MP3 Music Downloads

Preview songs, Download Free Music,Burn CDs at ITunes.com
iTunes_RGB_9mm

 


Google




InformationQuickFind.com - Find Information Fast

Links