(String streamContents: [:stream | 'A series of words to be shuffled' substrings shuffled do: [:each | stream nextPutAll: each] separatedBy: [stream space]])
- Bert -
That's still a lot of typing for what most other languages call join. On of the first extentions methods I added to Collection was this..
join: aString ^String streamContents: [:stream | self do: [:each | stream nextPutAll: each asString] separatedBy: [stream nextPutAll: aString]]
Yep, I added String>>splitOn: aString and ArrayedCollection>>joinOn: aString.
very useful pair of goodies (and I got tired of typing componentsSeparatedByString: on nextstep).
We should adopt such a pair and put them in the standard image.
very useful pair of goodies (and I got tired of typing componentsSeparatedByString: on nextstep).
I found myself implementing a message called #fold: several times (I got the idea from functional languages like Haskell, that provide such a function in their standard library), allowing to write the above problem like:
'A series of words to be shuffled' substrings shuffled fold: [ :a :b | a , ' ' , b ].
A possible implementation of #fold: could look like:
SequenceableCollection>>fold: aBlock | result | result := self first. 2 to: self size do: [ :index | result := aBlock value: result value: (self at: index) ]. ^ result.
Summing up the numbers from 1 to 100 can be done as easily as:
(1 to: 100) fold: [ :a :b | a + b ].
I think this is much more useful and generic than to add string specific functions like #join:, #joinOn:, ...
Lukas
-- Lukas Renggli http://www.lukas-renggli.ch
Lukas Renggli wrote:
Summing up the numbers from 1 to 100 can be done as easily as:
(1 to: 100) fold: [ :a :b | a + b ].
This is similar to what's called "reduce" in the functional-programming world; a true fold needs to take a seed as well,
(1 to: 100) fold: 0 by: [:a :b| a + b]. (1 to: 100) fold: [:a :b| a + b] with: 0.
for instance. Then of course you get the left-fold/right-fold distinction, and quickly veer off into category theory from whence none have returned.
Tony
This is similar to what's called "reduce" in the functional-programming world;
Yeah, that would be a better name.
a true fold needs to take a seed as well,
Then it is an #inject:into:
Lukas
-- Lukas Renggli http://www.lukas-renggli.ch
squeak-dev@lists.squeakfoundation.org