Encyclopedia > Closure (programming)

  Article Content

Closure (computer science)

Redirected from Closure (programming)

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++ and Visual Basic. Java supports a limited form called inner-classes, whereby the 'closures' exist as instances of a class, including references to the lexical environment (though only to those lexical variables which have suitable extent, ie. final variables, final parameters, and instance or class variables); strictly speaking though, Java does not support standalone functions, therefore it does not support closures in that sense.

See also functional programming.



All Wikipedia text is available under the terms of the GNU Free Documentation License

 
  Search Encyclopedia

Search over one million articles, find something about almost anything!
 
 
  
  Featured Article
U.S. presidential election, 1804

... Mate(Electoral Votes) Thomas Jefferson (W) 162 Democratic-Republican George Clinton (162) Charles C. Pinckney[?] 14 Federalist Rufus King (14) Other ...

 
 
 
This page was created in 22.2 ms