[squeak-dev] Collection>>sum implementation

Tony Garnock-Jones tonyg at lshift.net
Mon Aug 11 16:07:07 UTC 2008


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.




More information about the Squeak-dev mailing list