Haskell (and many other functional languages, I'm sure) features a number of fold functions, which accumulate list values into a scalar using a given operation. I find folds to be really handy. Here, then, are Perl implementations of Haskell's foldl, foldl1, foldr, and foldr1 functions (see The Haskell 98 Language Report for more on Haskell and its folds).
This isn't exactly elegant, robust, or thoroughly-tested code, but what the hell, it might be handy....
#! /usr/bin/perl -w use strict; use Test; sub foldl { my ($fn, $base, @list) = @_; foreach my $foo (@list) { $base = &$fn($base, $foo); } return $base; } sub foldl1 { my ($fn, @list) = @_; my $base = shift @list; return &foldl($fn, $base, @list); } sub foldr { my ($fn, $base, @list) = @_; foreach my $foo (reverse @list) { $base = &$fn($foo, $base); } return $base; } sub foldr1 { my ($fn, @list) = @_; my $base = pop @list; return &foldr($fn, $base, @list); } BEGIN { plan tests=>4 } ok(&foldl (sub {$_[0] - $_[1]}, 11, (1..10)), -44); ok(&foldl1(sub {$_[0] - $_[1]}, (1..10)), -53); ok(&foldr (sub {$_[0] - $_[1]}, 11, (1..10)), 6); ok(&foldr1(sub {$_[0] - $_[1]}, (1..10)), -5);
In reply to Haskell-style list folding by FoxtrotUniform
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |