I assume you've read Why I like functional programming.
Functional programming is where you treat functions like data. That is, you have functions that take functions as arguments and return functions as values. Just using pointers to functions (a.k.a. code references in Perl) allows you to do that to some extent, but not enough to really call it functional programming.
What closures add is the ability to give a subroutine attributes (or rather, add attributes to a reference to a subroutine). So you can write a subroutine that takes arguments and returns a subroutine that has those arguments as parameters. The usual example seems to be:
which also shows how Perl isn't a functional programming language but only allows you to use some functional programming techniques. - tye (but my friends call me "Tye")sub generateMultiplier { my( $byWhat )= @_; return sub { my( $toBeMultiplied )= @_; return $toBeMultiplied * $byWhat; } } my @list= ( 1, 2, 3, 5, 7, 11 ); my $doubler= generateMultiplier( 2 ); my $tripler= generateMultiplier( 3 ); my @twice= map $doubler->($_), @list; my @thrice= map $tripler->($_), @list;
In reply to (tye)Re: Why Closures?
by tye
in thread Why Closures?
by mothra
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |