in reply to Re: More functional programming utilities
in thread More functional programming utilities

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

Replies are listed 'Best First'.
Re^3: More functional programming utilities
by Roy Johnson (Monsignor) on Jun 08, 2005 at 15:38 UTC
    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

        One minor trap with the XS equivelents in Util.xs is that they don't necessarily respect "magic". So for instance if your data is tied, or whatnot you'll find that the XS routines don't play nicely. The perl implementations on the other hand do not suffer this problem.

        ---
        $world=~s/war/peace/g