[squeak-dev] Collection>>sum implementation
Jason Johnson
jason.johnson.081 at gmail.com
Mon Aug 11 11:57:54 UTC 2008
Hello all,
In my explorations today I happened on the implementation of the #sum method:
Collection>>sum
"This is implemented using a variant of the normal inject:into: pattern.
The reason for this is that it is not known whether we're in the normal
number line, i.e. whether 0 is a good initial value for the sum.
Consider a collection of measurement objects, 0 would be the unitless
value and would not be appropriate to add with the unit-ed objects."
| sum sample |
sample _ self anyOne.
sum _ self inject: sample into: [:accum :each | accum + each].
^ sum - sample
Personally, I view the code in the core image to, among other things,
serve the role of showing new Smalltalk programmers good ways of using
the language. This is exactly the kind of thing I would *not* want
people to see.
The obvious issue here is that #inject:into: doesn't fit this case
very well. But rather then go to these kinds of steps a much better
solution would be to simply notice that a specialized variation of
#inject:into: (that is in fact quite common) is needed here. Namely
a reduction method that just uses the first element as the starting
value, conceptually:
Collection>>reduce: aBlock
^ self allButFirst inject: self first into: aBlock
As it turns out there exists a more efficient implementation of this
method in Lukas' Magritte-Model package. I would propose his method
be promoted to a core method so #sum could be rewritten as:
sum
"sum the reciever"
^ self reduce: [:accum :each| accum + each ]
Thanks,
Jason
More information about the Squeak-dev
mailing list
|