Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Currying--useful examples?

by Errto (Vicar)
on Jan 11, 2007 at 00:56 UTC ( #594040=note: print w/replies, xml ) Need Help??

in reply to Currying--useful examples?

Another typical example involves higher-level functions like map. If map in Perl were curried then I could say something like:
# contrived my $incAll = map { $_++ }; my @data = return_some_numbers(); my @data2 = return_some_other_numbers(); $incAll->(@data); $incAll->(@data2);
and now I would have both of my arrays incremented by 1 across all their elements. Better yet, I could combine it with closures to create incrementors by an arbitrary value:
sub makeIncr { my $incr = $_[0]; return map { $_ += $incr }; }
In my own experience, I use currying and partial invokation extensively in Haskell which has native syntactic support for them, but so far I have not really come across them in my own Perl work.

Replies are listed 'Best First'.
Re^2: Currying--useful examples?
by tsee (Curate) on Jan 11, 2007 at 08:34 UTC

    It's really quite simple to write a curry-able map in Perl. I'd expect it to be pretty slow, though, because of the many subroutine calls: 2+n for a list of n elements. If "map CODE, LIST" treats CODE as a subroutine, that makes 2+2*n calls.
    And $_++ won't work.

    use strict; use warnings; sub cmap (&) { my $map = shift; return sub { map $map->($_), @_ }; } my $incr = cmap {$_*2}; print join " ", $incr->(2..5); print "\n"; # 4 6 8 10


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://594040]
[Discipulus]: stonecolddevin which style of kung-fu do you practice?
[stonecolddevin]: Discipulus i don't practice anymore but i studied Pai Lum, it was a mish mash of northern and southern. lots of emphasis on the 5 animals

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (12)
As of 2017-11-22 19:06 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (327 votes). Check out past polls.