[squeak-dev] Re: Collection>>sum implementation

Andreas Raab andreas.raab at gmx.de
Tue Aug 12 18:02:49 UTC 2008


Randal L. Schwartz wrote:
>>>>>> "Ramon" == Ramon Leon <ramon.leon at allresnet.com> writes:
> 
> Ramon> +1 on this, most idiomatic looking solution so far since using ifNil: is a
> Ramon> common idiom for defaulting a value.  It also properly handles collections
> Ramon> which might contain nil's by skipping over the nil while summing without
> Ramon> assuming any ordering by trying to use #first.
> 
> Not really.  It actually makes nil a special positional value.

I think we'll have to agree that the result is undefined if the 
collection contains elements that can't be summed up. While one can 
rewrite the method to deal with the specific problem you are describing 
like here:

Collection>>sum
    "Answer the sum of elements, or nil if empty"
    | first sum |
    first := true.
    self do:[:each|
      first
        ifTrue:[sum := each. first := false]
        ifFalse:[sum := sum + each]].
   ^sum

such that

   {nil. 3} sum. => Error
   {3. nil} sum. => Error

it just seems to me that the result of, e.g.,

  #() sum => nil
  {nil} sum => nil

is just as bad. I think that every proposed implementation has problems 
similar to these and I don't think it's addressable without unreasonable 
burden on both elements as well as implementation.

Cheers,
   - Andreas



More information about the Squeak-dev mailing list