Is there some functions like zip and fold in Perl?

≯℡__Kan透↙ 提交于 2019-12-12 12:11:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!