[squeak-dev] Collection>>sum implementation

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


On Mon, Aug 11, 2008 at 6:07 PM, Tony Garnock-Jones <tonyg at lshift.net> wrote:
> Jason Johnson wrote:
>>
>> sum
>>     "sum the reciever"
>>     ^ self reduce: [:accum :each| accum + each ]
>
> Yuck. (Not to the solution, necessarily, but to the whole idea of "sum".)
>
> This is the kind of problem that can't be solved well without a
> type-inferencing system (for instance, Haskell can implement polymorphic sum
> over possibly-empty lists well, so long as the instance of the type class of
> the elements of the collection has a definition for an appropriate zero), or
> explicit guidance from the programmer.
>
> sumWithZero: aZero
>  ^ self inject: aZero into: [:accum :each | each + accum]
>
> ...and remove sum entirely. Note that sum doesn't work on empty collections
> (!) but sumWithZero: does.

I think I understand what you're saying, but I disagree.  In a late
bound system we try it and if the types are not what our code expected
it fails.

In this case the only problem is the case of:        #() sum.
The problem is we don't know what type of objects the collection was
expected to have (and the collection could be hetrogenious anyway) so
there is no suitable "nothing" answer.  So I would propose that #sum
on an empty collection is simply an error (and I believe later in the
list it is said to actually do that).



More information about the Squeak-dev mailing list