[squeak-dev] Re: Collection>>sum implementation
Andreas Raab
andreas.raab at gmx.de
Tue Aug 12 16:39:44 UTC 2008
Colin Putney wrote:
> This is a bit like the #join: debate that comes up every now and then
> when a Ruby/Python/Perl ex-pat asks how it is that we don't have a
> method for joining an array of strings into a single string. The short
> answer is that it's because #join: only makes sense when all the
> elements of a collection are strings, and therefore, it's bad design.
I have to disagree. Have you ever looked at the senders of
do:separatedBy: (which is the easiest way to find lots the places that
would be improved by join)? For example:
ClassDscription>>instanceVariablesString
"Answer a string of my instance variable names separated by spaces."
^String streamContents: [ :stream |
self instVarNames
do: [ :each | stream nextPutAll: each ]
separatedBy: [ stream space ] ]
Why should code like this be duplicated throughout the system? If the
requirement is that join: is only to join strings (which is fine with
me) then convert the input to strings! It's simple, see:
SequenceableCollection>>join: delimiter
"Join the elements of the receiver using the given delimiter"
^String streamContents:[:s|
self do:[:each| s nextPutAll: each asString]
separatedBy:[s nextPutAll: delimiter asString]].
and the first example becomes:
ClassDescription>>instanceVariablesString
"Answer a string of my instance variable names separated by spaces."
^self instVarNames join: ' '
This is a muchly improved version as far as I am concerned.
> This is similar. I'd say the best way to improve #sum would be to delete
> it.
It is indeed similar. In such that Collection>>sum is just as useful a
utility that should be supported as well. I see no problem in requiring
that #sum is only valid for non-empty input and the result is undefined
(returning, nil, 0, or an error) if used on an empty collection.
Cheers,
- Andreas
More information about the Squeak-dev
mailing list
|