Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Golf: Adding up array elements

by kwaping (Priest)
on Nov 02, 2005 at 16:39 UTC ( [id://504986]=perlquestion: print w/replies, xml ) Need Help??

kwaping has asked for the wisdom of the Perl Monks concerning the following question:

Is there a shorter way to write this? Bonus points if it executes faster. Golf away!
my @array = (1,3,5,6); print sum(@array); sub sum { my $total = 0; foreach (@_) { $total += $_; } return $total; }

Replies are listed 'Best First'.
Re: Golf: Adding up array elements
by Limbic~Region (Chancellor) on Nov 02, 2005 at 17:23 UTC
Re: Golf: Adding up array elements
by Roy Johnson (Monsignor) on Nov 02, 2005 at 16:48 UTC
    There is a sum function in List::Util.

    Caution: Contents may have been coded under pressure.
Re: Golf: Adding up array elements
by Skeeve (Parson) on Nov 02, 2005 at 16:48 UTC
    I assume you mean to shorten the sub!?
    sub sum{eval join"+",@_}

    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
      eval join"+",@_

      Of course, that's not safe if @_ includes a text element with a ";" in it.

      But in the spirit of silly shortenings, how about some recursion?

      sub sum { @_ && pop(@_) + sum(@_) }

      -xdg

      Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

        Regarding recursion: I also thought about it, but it's longer. Your's can be shortened:

        sub sum {@_&&(pop)+sum(@_)}


        s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
        +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re: Golf: Adding up array elements
by ioannis (Abbot) on Nov 02, 2005 at 16:57 UTC

    Besides brevity, it might also execute faster since Util.xs informs us that sum() is coded in C, as NV sum(...)

    use List::Util qw(sum); print sum (my @arr = qw( 1 3 5 6));
Re: Golf: Adding up array elements
by jeffa (Bishop) on Nov 02, 2005 at 16:42 UTC

    I was never very good at Golf, but here goes:

    perl -le'@_=1..5;$s+=$_ for@_;print$s'

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Golf: Adding up array elements
by Perl Mouse (Chaplain) on Nov 02, 2005 at 16:48 UTC
    perl -le'@a=(1,3,5,6);$"="+";print eval"@a"' perl -le'@a=(1,3,5,6);$,="+";print@a'|bc
    Perl --((8:>*
Re: Golf: Adding up array elements
by ambrus (Abbot) on Nov 03, 2005 at 09:02 UTC

    This is not exactly golf, and works only for nonnegative integers.

    #!perl use warnings; use strict; { my $adder = ' G s/^ *\([0-9]*\) *\n\([0-9]*\)$/0\1pm0\2nb0/;td;d; :d;s/n\(\(b\).*0\|\)[^0]*$/nb98765432109876543210a0123456789\2 +/; s/\(.\)\(p.*\)\(.\)\(n.*\1\).*a.*\3/\2\4\3/; s/^0*\(.*\)p\(.*m\)0*\(.*\)\(.\).\{11\}$/0\1p\4\20\3/; /m0*n.*0/!bd; s/^\(.*\)p\(.*\)m.*/\1\2/;s/^0*//; h;$!d '; $adder =~ s/;/\n/g; # some seds don't like semicolons sub printsum { open my $SED, "|-", "sed", $adder or die "error running sed: $ +!"; print $SED int($_), "\n" or die "error writing to sed: $!" for @_; close $SED or die "error closing sed: $!"; } } my @array = (1,3,5,6); printsum(@array); __END__

    Update 2007-12-06: see Re^2: --- adding a column of integers

    Update 2011-10-29: see also (almost) foldl.

      Not golf at all, but an excellent obfuscation! :)
Re: Golf: Adding up array elements
by Aristotle (Chancellor) on Nov 02, 2005 at 21:20 UTC

    The obvious way to golf it:

    sub sum { my$t;$t+=$_ for@_;$t }

    The eval approaches are shorter, but unsafe. It’s your call whether that’s acceptable. For real code, it’s not. But in real code I’d use List::Util.

    Update: added space as per sauoq.

    Makeshifts last the longest.

      Obvious, maybe... but not quite correct. You need a space before your for.

      -sauoq
      "My two cents aren't worth a dime.";
      

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://504986]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-20 11:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found