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

Jason Johnson jason.johnson.081 at gmail.com
Tue Aug 12 07:12:16 UTC 2008


On Tue, Aug 12, 2008 at 6:08 AM, Jerome Peace
<peace_the_dreamer at yahoo.com> wrote:
> [squeak-dev] Re: Collection>>sum implementation
> Klaus D. Witzel klaus.witzel at cobss.com
> Mon Aug 11 22:56:40 UTC 2008
>
> Currently summing over the empty list signals an error.
> That seems right.
>
> If something needs the behavior otherwise it could wrap a call to sum with a check for special conditions
> such as isEmpty or isNil. Then just return the special answer with a guard clause.

Agreed.

> RandaL wrote:
>> This presumes that anything that implements #+ is also expected
>> to implement #-.
>
> Yes. #sum currently is spec'ed to assume that anyway.

And that's wrong.  A sensible implementation of #sum should not need
subtraction!

>>Yes, that was also present in the original implementation,
>> but a version that doesn't require that would be nice.
>
> Why?
> And why program it before it is needed?
>
> And please look at the mantis report. It shows why the fix is needed.

*sigh*  Please read my message.  It is *obvious* that plain old
#inject:into: can't be used for #sum.  The solution is to have a new
method that fits the case better (e.g. #reduce: aBlock), not add an
element of the list in twice then take it out again.

Here is Lukas' implementation of SequencableCollection>>reduce:

reduce: aBlock
	| result |
	result := self first.
	2 to: self size do: [ :index |
		result := aBlock
			value: result
			value: (self at: index) ].
	^ result

You see?  We take an element from the receiver as we must for the
reasons mentioned in the mantis report, *but we don't double process
it and we don't have to take it back out again*.  Simple and elegant
and also handles the case of an empty list with a sensible error
(#first fails with a bounds error).



More information about the Squeak-dev mailing list