Talk:Closure (computer programming)

This is an old revision of this page, as edited by Toby Bartels (talk | contribs) at 04:28, 29 October 2002 (Remove material from Talk:Closure.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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.

bjt