[squeak-dev] removing from a collection while enumerating it

Bob Arning arning315 at comcast.net
Thu Jul 4 15:46:45 UTC 2013


One thing to note is that the collection is messed up while in the midst 
of removal:

a _ #(1 2 3 4 5) asOrderedCollection.
a removeAllSuchThat: [ :each |
     Transcript show: a asString; cr.
     each odd
].
Transcript show: a asString; cr.

so, if your #doSomething were to examine the collection, it might get 
the wrong impression.



On 7/4/13 11:30 AM, Chris Muller wrote:
> Hm, I did not know about removeAllSuchThat:, but in looking at it, I
> find two things "wrong" with it.  1) the superclass implementation in
> Collection makes a copy of the collection, which is the basis of my
> reason to use reverseDo: instead of enumerating a copy myself.
>
> But I'm using an OC and OC overrides it without making the copy.
> That's good, but I also need to know which elements were removed.  I
> ended up doing it like:
>
>    myCollection removeAllSuchThat: [ : each | each meetsMyCondition
> and: [ each doSomething.  true ] ]
>
> I think it would be nice if removeAllSuchThat: could be similar to
> remove: in this respect, but at least, unlike Java, Smalltalk lets me
> put any "doSomething" expression in the block as long as it finally
> evaluates to a boolean.
>
> Thanks.
>
> On Wed, Jul 3, 2013 at 4:19 PM, Bert Freudenberg <bert at freudenbergs.de> wrote:
>> On 03.07.2013, at 11:27, Chris Muller <asqueaker at gmail.com> wrote:
>>
>>> I have a case where I need to remove certain entries from an
>>> OrderedCollection that will be called very frequently.  I therefore
>>> want to avoid copying the collection (to safely remove while
>>> enumerating) but it seems #reverseDo: can do what I want.
>>>
>>>   myCollection reverseDo: [ : each | each meetsSomeCriteria ifTrue: [
>>> myCollection remove: each ] ]
>>>
>>> Does anyone see any problem with doing this?
>> What's wrong with removeAllSuchThat:?
>>
>> - Bert -
>>
>>
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.squeakfoundation.org/pipermail/squeak-dev/attachments/20130704/4a710d35/attachment.htm


More information about the Squeak-dev mailing list