Jump to content

Closure (computer programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Toby Bartels (talk | contribs) at 03:10, 16 July 2002 (From Closure.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

In certain programming languages, such as Scheme or Perl, a closure is a function, together with the lexical environment that it was created with. Some people will call any data structure that binds a lexical environment a closure, but it usually refers specifically to functions. There can be multiple instances of a function at once, each of which has its own private state in its bound environment. Less commonly, multiple functions can be produced which close over the same environment, enabling them to communicate privately by altering that environment. Here is a short but non-trivial example in Perl.

# Takes a function and a list of anonymous arrays.
# Returns a closure that will, when called, call that function
# with each combination of values from the arrays.
sub bind_loops {
  my $fn = shift;                 # The function we are passed
  my $range = shift;              # The first anonymous array
  my $sub = sub {                 # The closure we are producing
    $fn->($_, @_) for @$range     # $range is from the closed over environment!
  };
  return @_                       # Are there more arguments?
    ? bind_loops($sub, @_)        #   If so, then recursively bind the other arrays
    : $sub;                       #   Else, this closure is the answer
}

# Create the closure
my $closure = bind_loops(
 sub {print "@_\n";},             # This function just prints its arguments
  [1..2], ['a'..'c'], ['A'..'D']  # anonymous arrays
);

# Call it
$closure->();                     # Prints all 24 combinations

As this example shows, closures encourage a different style than procedural programming or object-oriented programming. This style is often associated with Scheme, however it translates well in any language which supports both lexical variable scoping and anonymous functions.

Current languages which support closures include JavaScript, Perl, Ruby, Scheme, and Smalltalk. Ones which do not include C, C++, Java and Visual Basic.

See also functional programming.