Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

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 "", '.


Comment on Re: (almost) foldl
Download Code
Re^2: (almost) foldl (""=>())
by tye (Cardinal) 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?
      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.
      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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://908596]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (11)
As of 2014-12-26 21:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (176 votes), past polls