[Newbies] Deleting elements from a Collection while looping
lars.wassermann at student.hpi.uni-potsdam.de
Sat Dec 10 18:55:22 UTC 2011
changing a list you are iterating over is not a good idea.
Maybe return the changed list and save the changed list where the
parameter comes from:
^ aSet select: [ :block | block fall ]
Another possibility would be iterating and afterwards deleting the
entries. But this is slower
aSet removeAll: (aSet reject: [ :block | block fall ])
Am 10.12.2011 20:43, schrieb Jan Teske:
> I have a question concerning the behavior of Collections in Squeak.
> Recently I face a problem when trying to delete some elements from a set
> during a 'do:' message.
> Have a look at this sample method:
> doFallForAllIn: aSet
> aSet do:
> [:block | block fall ifFalse: [aSet remove: block]]
> It loops over a set of blocks and performs the fall message on each of
> them. If a block is not falling I don't want it to be in aSet after the
> function returned so I remove it from the set. Squeak doesn't seem to
> like that since some rather strange error now occures: If a block is
> removed from the set, the next block in the set will be left out from
> looping... sometimes. Nearly all the time it works as exspected, only
> sometimes a block is ignored. I couldn't find any pattern when this happens.
> So my question is: Has anyone an explanation for this? Does the error
> occure because the way I'm doing it is fundamentally wrong? Or am I just
> overlooking something and it is possible to remove blocks from a
> collection while looping over it?
> Thanks in advance!
> Beginners mailing list
> Beginners at lists.squeakfoundation.org
More information about the Beginners