Redirected from Closure (programming)
# 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 combinationsAs 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.
Search Encyclopedia
|
Featured Article
|