in reply to Why Closures?
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;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re (tilly) 2: Why Closures?
by tilly (Archbishop) on Apr 26, 2001 at 21:33 UTC | |
by tye (Sage) on Apr 26, 2001 at 21:45 UTC | |
by dws (Chancellor) on Apr 26, 2001 at 21:36 UTC | |
by tilly (Archbishop) on Apr 27, 2001 at 01:24 UTC | |
Re: (tye)Re: Why Closures?
by jdporter (Paladin) on Nov 05, 2002 at 16:35 UTC | |
by Jenda (Abbot) on Nov 05, 2002 at 22:04 UTC | |
by jdporter (Paladin) on Nov 05, 2002 at 22:19 UTC | |
by Jenda (Abbot) on Nov 06, 2002 at 17:24 UTC | |
by Aristotle (Chancellor) on Nov 06, 2002 at 20:24 UTC | |
|