How to replenish the collection back without copies?

I would like to know how to transfer the collection back without copies to Pharo / Squeak.

For example, for stream #(1 2 3) , so stream next returns 3 , then 2 , then 1 . I know that I can just use collection reversed readStream , but reversed copies.

+5
source share
3 answers

Create the RevertingCollection class as a subclass of SequeanceableCollection with one collection instance variable. Now define these three methods (instance side):

 on: aCollection collection := aCollection size ^collection size at: index ^collection at: self size - index + 1 

Done. Now you can do the following:

 stream := (RevertingCollection new on: #(1 2 3)) readStream. 

and you will get

 stream next "3". stream next "2". stream next "1" 

You can go ahead and implement the message

 SequenceableCollection >> #reverseStream ^(RevertingCollection new on: self) readStream 

So it all comes down to just

 #(1 2 3) reverseStream 

ADDITION

As indicated in the comments, there are no two parts that are:

1. Instance creation method (class)

 RevertingCollection class >> #on: aCollection ^self new on: aCollection 

With this addition, the above method should be rewritten as follows:

 SequenceableCollection >> #reverseStream ^(RevertingCollection on: self) readStream 

Note. Other small traders would prefer this method to be called #withAll:

2. The following copy method:

 RevertingCollection >> #copyFrom: start to: stop | n | n := self size. copy := collection copyFrom: n - stop + 1 to: n - start + 1. ^self class on: copy 

This method is required to support #next: in the reverse read stream.

+3
source

You can use the generator:

 | coll stream | coll := #(1 2 3). stream := Generator on: [:g | coll reverseDo: [:ea | g yield: ea]]. stream next 

Generators allow you to basically wrap the stream interface around any part of the code.

+3
source

I have three options:

  • Modify your code to use #reverseDo:
  • Use Xtreams
  • Create your own thread.
+2
source

Source: https://habr.com/ru/post/1215795/


All Articles