Do you know where your variables are? PerlMonks

### Re: (almost) foldl

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

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.

Create A New User
Node Status?
node history
Node Type: note [id://908596]
help
Chatterbox?
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
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
In order to be able to say "I know Perl", you must have:

Results (328 votes). Check out past polls.

Notices?