in reply to List::Util::sum() and empty lists...

I'm not saying it's the right solution in the long term, but you can avoid the problem by always passing a constant zero as the first argument to sum. It has no affect upon the result, but does the right thing if the rest of the list is empty.

print sum 0, ();; 0

Similarly, passing a constant 1 as the first term to reduce if your using it to calculate product(), and the appropriate identity as the first term for other operations avoids the need for tests, or the generation of warnings.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^2: List::Util::sum() and empty lists...
by Fletch (Bishop) on Dec 03, 2006 at 15:19 UTC

    Yeah, the Ruby way to do this is to use inject and pass the appropriate seed value for the operation. If you don't like the explicitness there you can always hide it by extending Enumerable yourself.

    module Enumerable def sum( ) inject( 0 ) { |m,x| m += x } ; end def prod( ) inject( 1 ) { |m,x| m *= x } ; end end

    Additionally: As to the original question (changing to return 0 by default), you kind of loose information that way in that you don't know if you had an empty list versus having a list which just happened to sum to zero. Of course you could always explicitly check for that (presuming you have the original list around) if you needed to know. (So chalk this up as a wishy washy non-comittal neither condemnation nor approval of the proposal. :)

Re^2: List::Util::sum() and empty lists...
by blazar (Canon) on Dec 04, 2006 at 08:18 UTC
    I'm not saying it's the right solution in the long term, but you can avoid the problem by always passing a constant zero as the first argument to sum. It has no affect upon the result, but does the right thing if the rest of the list is empty.

    Nice trick (albeit still a trick) BrowserUk++, I must admit that simple and intuitive as it is, I hadn't thought about it: it's much lighter than say || 0, also having the big advantage of not creating problems with precedences and such.