in reply to scalarmap - some new perl syntax

What a great idea. In fact, it's so great, it's already been implemented (in C, with a fallback to Perl if the C fails to load) at List::Utils under the name reduce.

And the reduce operator is one of the ideas to add into Perl6, so eventually we won't even need to get into a module. {grin}

Something tells me that there isn't enough searching of the existing cool stuff in the CPAN going around. {grin}

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
RE: RE: scalarmap - some new perl syntax
by ncw (Friar) on Sep 01, 2000 at 11:27 UTC
    I might have known that there would be a CPAN thingy to do it, and that merlyn would know of it {grin} ;-)

    Reduce is a much better name. It calls your sub with $a and $b set to the first two elements of the array which is neater in some ways, but would make it harder to write the factorial example above.

    Here is a related question - I tried to write the subroutine above with the paramters ($&@) but I couldn't then call the subroutine - looks like a bug... (I posted an example of this a bit further up the thread)

    BTW it is List::Util

      You wrote:
      > It calls your sub with $a and $b set to the first two > elements of the array which is neater in some ways, > but would make it harder to write the factorial example > above.
      How so? Your initial value is, in this case, really just the first element of the array, in the case of reduce (I didn't realize this until looking at reduce, granted). So you'd just make your array 1..$N for a factorial. Like this:
      sub factorial { reduce { $a * $b } 1..$_[0] }
        Yes you are right!

        Having an extra parameter on scalarmap is exactly equivalent to adding this parameter onto the front of the list you pass to reduce.

        EG

        $z = scalarmap { $a * $b } 1, 2..10; # is the same as use List::Util; $z = reduce { $a * $b } 1, 2..10;
        All hail to perl's unfancy list flattening subroutine parameter passing!

        This makes scalarmap completely redundant :-( It was fun inventing it though :-)