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:
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;
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")
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.