问题
I want to use some function such as "zip", "fold" and "map" in perl. (Just like in Haskell.) I found map and it works well. Then, is there zip and fold? Thank you very much.
回答1:
I've implemented many of those functions (and even Haskell-like lazy ones) in my module List::Gen
use List::Gen qw(zip reduce);
my @list = zip [1 .. 4], ['a' .. 'd'];
my $str = reduce {$a . $b} @list;
say $str; # 1a2b3c4d
Or using the glob
function to build the ranges:
use List::Gen 'glob';
say <1 .. 4>->zip(<a .. d>)->reduce('$a.$b'); # 1a2b3c4d
Using ->reduce('.')
or ->reduce(sub {$a . $b})
also works.
Or if you are golfing:
say <[.]>->(<1..4>|<a..d>);
Or for the Haskell versions, see List::Gen::Haskell
回答2:
The List::Util library includes reduce()
, which does essentially what fold
does.
List::MoreUtils contains a zip()
function.
Neither is built-in, mostly because Perl is not a functional programming language.
回答3:
If you're interested in using functional programming concepts in Perl, then I highly recommend that you read Higher Order Perl.
回答4:
Modules that provide functional programming tools:
- Perl's map and grep
- List::Util
- List::MoreUtils
- List::Gen and List::Gen::Haskell (including lazy lists)
- Algorithm::Loops
You might also be interested in the (now free to download) book Higher Order Perl.
来源:https://stackoverflow.com/questions/9115666/is-there-some-functions-like-zip-and-fold-in-perl