[squeak-dev] Re: Collection>>sum implementation
Klaus D. Witzel
klaus.witzel at cobss.com
Tue Aug 12 11:32:55 UTC 2008
On Tue, 12 Aug 2008 09:28:22 +0200, Andreas Raab 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"
Sure that is :)
> 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].
I *love* that elegant use of the power of nil :)
[and I would object accessing inexisting elements for forcing an Error :( ]
big + 1, excellent implementation Andreas
> (assumes unit package with Euro support loaded).
>
> Cheers,
> - Andreas
>
More information about the Squeak-dev
mailing list
|