[squeak-dev] Collection>>sum implementation
Tony Garnock-Jones
tonyg at lshift.net
Tue Aug 12 09:30:37 UTC 2008
Jason Johnson wrote:
> 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).
Yes, an error is currently signalled. Which makes the general case:
aCollection ifEmpty: [0] ifNotEmpty: [aCollection sum].
... which, to me, is a bad code smell. Then again, I've been an FPer for
a long while. The ifEmpty:ifNotEmpty: corresponds to a "reduce" in
SRFI-1 [1] terminology, rather than a proper "fold", and folds are
easier to use to write correct general code, in my experience.
Maybe sumWithZero: was a silly name -- sumFrom: is perhaps better? I
guess this is all bike-sheds, though, since #sum is firmly established,
awkwardness of type, of interface and of implementation notwithstanding.
sumFrom: x
^ self inject: x into: [:accum :each | accum + each]
Regards,
Tony
[1]: http://srfi.schemers.org/srfi-1/srfi-1.html
More information about the Squeak-dev
mailing list
|