Reduce in Perl

Perl has grep/map/sort since probably forever (actually, sort() starts appearing since Perl 2.0). But even now, reduce is still not a builtin in Perl 5 (though available via List::Util), so doing reduce is probably not something that comes as naturally to Perl programmers. Meanwhile Ruby, JavaScript, and even PHP have their reduce operation builtin.

But then, reduce is "not really that useful" (you can just replace it with a simple for loop). So much that Python 3.0 now removes the function from the global namespace and reduces it (pun intended) to a mere member of functools. I guess reduce is really handy only if you are in a heavily functional language that lacks procedural basics.

This can be thought of as a testament to the level of language design skill that Larry has.

The rather funny thing is, in Perl 6, in addition to the reduce() List method there is also the reduce ([]) metaoperator as well.

3 Comments

In Smalltalk, reduce is spelled "inject: ... into: [ ... ]", and thus avoids the nasty question "what if we have too few elements to do any operation in the first place?", which reduce always has to answer.

Interestingly enough, I was recently bemoaning, in the Perlmonks CB, the lack of a built-in reduce (aka fold) function to go along with map and grep (aka filter) functions. All of the functions in List::Util (except reduce itself, and shuffle) can be implemented with reduce. It can also be useful for dynamically traversing deeply nested structures. map and grep can also be reduced to simple foreach loops, but they are still useful, as is reduce.

Leave a comment

About Steven Haryanto

user-pic A programmer (mostly Perl 5 nowadays). My CPAN ID: SHARYANTO. I'm sedusedan on perlmonks. My twitter is stevenharyanto (but I don't tweet much). Follow me on github: sharyanto.