On Thu, Apr 2, 2015 at 8:22 AM, Peter Uhnák <i.uh...@gmail.com> wrote:

> Hi,
>
> I've just run into quite a nasty surprise
> ~~~~~~~~~~~~~~~~
> col := #(1 2 3 4 5) asOrderedCollection.
> col do: [ :each | col remove: each. ].
> col
> ~~~~~~~~~~~~~~~~
> it throws "NotFound: nil not found in OrderedCollection"
> I tested it also in Pharo3 and there it just silently removed first, third
> and fifth element.
>
> Looking at the implementation of OrderedCollection>>do:  it seems that
> doing what I'm doing is a bad idea.
>
> So what shall one do:? col copy do: [...] ?
>

Yes, as a general rule, do not modify a collection you are iterating on,
so, doing col copy do: looks right.

removeAllSuchThat: aBlock
"Evaluate aBlock for each element and remove all that elements from
the receiver for that aBlock evaluates to true.  Use a copy to enumerate
collections whose order changes when an element is removed (i.e. Sets)."

self copy do: [:each | (aBlock value: each) ifTrue: [self remove: each]]

If the collection is huge, that can be an issue.


> Why can't do: be a bit smarter? Optimization?
>

If you have the group of things to remove you can do

aCollection removeAll: anotherCollection

Phil


>
> Thanks,
> Peter
>

Reply via email to