Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re: (almost) foldl

by Grimy (Pilgrim)
on Jun 07, 2011 at 22:57 UTC ( #908596=note: print w/replies, xml ) Need Help??

in reply to (almost) foldl

Well, in unary, summing is as simple as concatenating. And Perl has a built-in decimal-to-unary converter (the x operator), as well as a built-in unary-to-decimal converter (the length function). Putting all this together:
my @list = (1, 2, 3, 4, 5); print length join "", map{"1" x $_} @list; #prints 15
But your implementation sure is fun :-) EDIT: Look at tye's code instead. This one is stupid. Don't know what I had in mind when I wrote 'length join "", '.

Replies are listed 'Best First'.
Re^2: (almost) foldl (""=>())
by tye (Sage) on Jun 08, 2011 at 02:24 UTC
    my @list = ( 1..6 ); print 0+map{(1)x$_}@list;

    - tye        

Re^2: (almost) foldl
by dk (Chaplain) on Jun 08, 2011 at 04:56 UTC
    negative numbers?
      my @list = ( -4 .. 6 ); print map((1)x$_,@list) - map((1)x-$_,@list);

      - tye        

        Wow. That's a exactly (and I mean, exactly) the first idea I had to solve the negative numbers problem. I didn't post it, though, because it doesn't handle decimal numbers.
      sub sum { eval 'pop(@_)+' x ($#_ + 1) . '0'; } @list = (-4, 15, -5, 2.5); print sum @list; # 8.5, as expected print sum -4, 15, -5, 2.5; # Works the same print sum; # 0 (not undef)
      EDIT: replaced $#list with $#_ , so that it works with lists of any length. Silly me.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://908596]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2017-11-23 04:39 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (328 votes). Check out past polls.