In perl at least, a closure doesn't have to be a function definition. It's more or less anything between a pair of braces, that serves as it's own variable scope. In Damian Conway's Object Oriented Perl, I believe he uses closures to implement the private variables of an object, so it might be misleading to say that the closure itself is an object or acts like one. In any case, something needs to be said about scope here. Wesley
How could one use a closure that's not a function definition?
Regarding the "acts as an object" comment, I was thinking of a closure like this:
sub counter { my $x = shift; return sub { print "$x\n"; $x--; }; } $h = counter(4); $g = counter(7); &$h(); # gives 5 &$h(); # gives 3 &$g(); # gives 7 &$h(); # gives 2
AxelBoldt
A closure can be used as a way to simulate static variables. For instance consider the following (slow) function:
sub fib { my $n = shift; if ($n <= 1) { return 1; } else { return fib($n-1) + fib($n-2); } }
It works, but calculating (say) fib(40) may take a while. Now let's add a private closure in which we cache results (this kind of caching is known as memoizing):
{ my %cache; sub fib { my $n = shift; if ($n <= 1) { return 1; } elsif (exists $cache{$n}) { return $cache{$n}; } else { return $cache{$n} = fib($n-1) + fib($n-2); } } }
Now the function runs much more quickly. If we had static variables (the "my $foo if 0;" bug does not count in my books!), that would be the right way to do this, but closures can do it as well.
BTW I hope that the example I gave is not too complex. I wanted to provide something that was accessible but gave an idea of why someone might choose to use closures.
Now that we have a nice amount of material on the programming sort of closure, I suggest that this should be moved to Closure_(programming), making Closure itself a disambiguation page. Objections? — Toby Bartels, Sunday, July 14, 2002
- I really can't think of which use the term could be considered to be the dominent one used in English, so I wouldn't object (as long as any resulting misdirected links are fixed). --maveric149
I'll certainly fix the links; I'm a responsible disambiguator ^_^. — Toby Bartels, Monday, July 15, 2002
As the newbie who added said material, I certainly don't object to refactoring it. --BJT