I would like to know how to stream a collection backwards without copies in Pharo/Squeak.
For example, to stream #(1 2 3)
so stream next
returns 3
, then 2
, then 1
. I know I could just use collection reversed readStream
, but reversed
copies.
Create the
RevertingCollection
class as a subclass ofSequeanceableCollection
with one instance variablecollection
. Now define these three methods (instance side):Done. You can now do the following:
and you will get
You can go a step further and implement the message
In this way everything reduces to just
ADDENDUM
As discussed in the comments there are two pieces missing here which are:
1. An instance creation method (class side)
With this addition the method above should be rewritten to:
Note: Other smalltalkers would prefer this method to be named
#withAll:
.2. The following method for copying:
This method is required to support
#next:
in the reverse read stream.There are three options off the top of my head:
#reverseDo:
You could use a Generator:
Generators let you wrap a streaming interface around any piece of code, basically.