[squeak-dev] Re: Collection>>sum implementation
Klaus D. Witzel
klaus.witzel at cobss.com
Mon Aug 11 22:56:40 UTC 2008
On Mon, 11 Aug 2008 22:47:25 +0200, Randal L. Schwartz wrote:
>>>>>> "Jerome" == Jerome Peace <peace_the_dreamer at yahoo.com> writes:
>
> Jerome> You let it tell you:
>
> Jerome> any := myCollection anyone .
> Jerome> zeroElement := any - any .
Problem here is that #() has no anyone, and so #negated (assuming that sum
wants to do #+) can also not be used.
> This presumes that anything that implements #+ is also expected
> to implement #-. Yes, that was also present in the original
> implementation,
> but a version that doesn't require that would be nice.
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.
This could be called an undefined object which understands #+ ;) clearly
*not* nil.
Such things can be avoided be passing the desired zero element to
#sumFromZero: and checking the answer, so that the sender can decide what
its own zero means for an empty collection.
But if you want #sum rather than #sumFromZero: then for the numerical case
it sufficies to do
mySalarySum := myBigSalaryVector sum + 0
, sufficient because mysticalObject, assuming that's what #sum can answer
for the empty collection, returns a copy of the extra 0 for the extra #+ ;)
And a comment in #sum's method can tell how to use it properly.
/Klaus
More information about the Squeak-dev
mailing list
|