Collecting Smalltalk idioms
Andrew C. Greenberg
werdna at gate.net
Tue Aug 10 13:09:08 UTC 1999
On the theory that there are no dumb questions -- and given my
experience that you men and women frequently take my breath with the
elegance of your solutions to my dumb questions:
In the silly Smalltalk tricks category, is there a "least ugly" way
to generate a comma separated list out of a collection? The pithy:
aCollection do:
[:each |
each printOn: aStream.
aStream nextPut: $,]
is of course flawed because it prints an extra comma at the end of
the collection. Assuming a SquenceableCollection,
aCollection allButLast do:
[:each |
each printOn: aStream.
aStream nextPut: $,].
aCollection last printOn: aStream
works, but (i) croaks on empty collections, (ii) unnecessarily copies
nearly the entire collection and (iii) offends my eyes. Other
approaches seemed even uglier to me.
s _ Stream on: aCollection.
[s atEnd] whileFalse:
[s next printOn: aStream.
s atEnd ifFalse: [aStream nextPut: $,]]
seemed less inelegant, albeit a bit busy and heavy-handed.
Of course, I can bury any ugliness, if necessary, just by adding a
#do:inbetween: method or the like to the Collection protocol. Is
that reason enough to change a core system class? Am I too shy about
that sort of thing?
Assume you have an application where you must be doing this sort of
thing a lot. Is there a preferred approach or idiom for this kind of
enumeration?
More information about the Squeak-dev
mailing list
|