in reply to More functional programming utilities

Check out Algorithm::Loops 'MapCar*' for parallel processing of lists (which would include transposing):
use Algorithm::Loops 'MapCar'; my $wide = [[1,2,3],[2,3,5]]; my $tall = [ MapCar {[@_]} @$wide ];
Your fold_left can be done exactly as you've written it using reduce. fold_right would require only one reverse. mult would be another reduce (as, internally, sum is). You could also do log math on sum. :-)

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: More functional programming utilities
by kaif (Friar) on Jun 08, 2005 at 14:03 UTC

    Thank you for finding MapCar. That does a lot of what I need.

    So yeah, I just realized that fold_left can be written by simply calling reduce with the same arguments (so that fold_left's initial becomes the first element of reduce's input). But fold_right does require two reverses, in the following sense: suppose I wanted to compare left- and right-associative subtraction. Then, I have to reverse once to change a call of fold_right into fold_left but then I also have to change the order of arguments into the block.

    Well, I really want sum to be reduce { $a + $b } 0, @input, so that would make multiplication reduce { $a * $b }, 1, @input. Note that sum is not reduce internally. Here's the code:

    sum(...) PROTOTYPE: @ CODE: { SV *sv; int index; if(!items) { XSRETURN_UNDEF; } sv = ST(0); RETVAL = slu_sv_value(sv); for(index = 1 ; index < items ; index++) { sv = ST(index); RETVAL += slu_sv_value(sv); } } OUTPUT: RETVAL
      Within List::Util source, sum is defined:
      sub sum (@) { reduce { $a + $b } @_ }
      Where is the code you quoted from?

      Caution: Contents may have been coded under pressure.

        You're right, but above that code, there's a notice saying

        # This code is only compiled if the XS did not load

        My code is from the XS. I can't seem to link to it online, but the filename should be Util.xs, I think.

        Update: Here's a link from CPAN: Util.xs

Re^2: More functional programming utilities
by ivancho (Hermit) on Jun 08, 2005 at 11:42 UTC
    nah, you can't, you'd also have to keep the sign information and short-circuit on 0s.. unless you promise to only multiply positive numbers..

    other than that, all points are spot on.