Simple String Question.
Richard A. O'Keefe
ok at cs.otago.ac.nz
Thu May 16 01:35:41 UTC 2002
cg at cdegroot.com (Cees de Groot) wrote:
And if you get bored with that, you might want to have some fun and implement
#, on WriteStream or maybe even on a special class (StringStream?) so you can
do something like
(StringStream , 'foo' , 'bar', 'baz') contents
Here it is in WriteStream:
WriteStream>>
, aCollection
^self nextPutAll: aCollection
WriteStream class>>
, aCollection
^(self on: (aCollection species new: 16)) , aCollection
Then
(WriteStream , #(f o o) , #(b a r) , #(u g h)) contents
=> #(f o o b a r u g h)
This is "cute", but not really a good idea. We _have_ a standard name
for the operation "add all these things to this stream" and it's #nextPutAll:
not #, . Using #, instead would just be confusing.
Here's a better approach:
SequenceableCollection>>
concatenationAs: aClass
"The receiver should be a sequence of sequences.
Return the concatenation of the receiver's element
as an instance of aClass, which should be a collection class."
"#('foo' 'bar' 'ugh') concatenationAs: Array"
|length result offset delta|
length := self inject: 0 into: [:sum :each | sum + each size].
result := aClass new: length.
offset := 0.
self do: [:each |
delta := each size.
result replaceFrom: offset + 1 to: offset + delta
with: each startingAt: 1.
offset := offset + delta].
^result
SequenceableCollection>>concatenation
"The receiver should be a sequence of sequences.
Return the concatenation of the receiver's elements
as an instance of the first element's species,
or as an Array if there is no first element."
"#((f o o) (b a r) (u g h)) concatenation"
self isEmpty ifTrue: [^#()].
^self concatenationAs: self first species
Then
{'foo'. 'bar'. 'baz'} concatenation
or in general
{s1. s2. .... sn} concatenation
will concatenate a bunch of strings with minimal overhead.
#replaceFrom:to:with:startingAt: is a primitive in Array and String,
so not only will the minimal amount of copying be done, but it
will be done about as fast as you _can_ do it in Squeak.
More information about the Squeak-dev
mailing list
|