[squeak-dev] Re: Collection>>sum implementation
Andreas Raab
andreas.raab at gmx.de
Tue Aug 12 07:28:22 UTC 2008
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
More information about the Squeak-dev
mailing list
|