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

Jason Johnson jason.johnson.081 at gmail.com
Tue Aug 12 13:01:52 UTC 2008


On Tue, Aug 12, 2008 at 9:28 AM, Andreas Raab <andreas.raab at gmx.de> wrote:
> Klaus D. Witzel wrote:
>>
>> Then use an object that for #+ returns a copy of the argument (no I'm not
>> mentioning nil :)
>>
>>  ^ myCollection inject: mysticalObject into: [:a :b | a + b]
>>
>> It *must* return some mysticalObject when myCollection is empty since one
>> cannot know the species of elements which are not in a collection.
>
> nil is actually a fine "mysticalObject" and it arises naturally in the
> implementation of #sum that I would favor:
>
> Collection>>sum
>    "Answers the sum of the elements in the receiver, nil if empty"
>    | sum |
>    self do:[:value|
>        sum := sum ifNil:[value] ifNotNil:[sum + value].
>    ].
>    ^sum
>
>> But if you want #sum rather than #sumFromZero: then for the numerical case
>> it sufficies to do
>>
>>  mySalarySum := myBigSalaryVector sum + 0
>
> With the above this becomes:
>
>  mySalarySum := myBigSalaryVector sum ifNil:[0 euro].
>
> (assumes unit package with Euro support loaded).
>
> Cheers,
>  - Andreas

Good insight, but also in this implementation you are doing an if
every time through the loop for a condition that can only happen at
the start of the iteration.  In the current implementation and my
proposal the size check happens at the start only once as a
consequence of taking the first element.

If one wanted to handle the empty list case without using exceptions I
think the common pattern would be #ifEmpty/ifNone, no?

So something like:

mySalarySum := myBigSarayVector sumIfEmpty: [0 euro]            "hrm,
how are the selectors generally named for this sort of case?"



More information about the Squeak-dev mailing list