Talk:Closure (computer programming): Difference between revisions

Content deleted Content added
No edit summary
No edit summary
Line 21:
 
[[user:AxelBoldt|AxelBoldt]]
 
A closure can be used as a way to simulate static variables. For instance consider the following (slow) function:
 
<pre>
sub fib {
my $n = shift;
if ($n <= 1) {
return 1;
}
else {
return fib($n-1) + fib($n-2);
}
}
</pre>
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):
<pre>
{
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);
}
}
}
</pre>
Now the function runs much more quickly. If we had static variables (the "my $foo if 0;" bug does <i>not</i> 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.
 
[[user:bjt|bjt]]