[Newbies] Deleting elements from a Collection while looping through it

michael rice nowgate at yahoo.com
Sat Dec 10 19:09:59 UTC 2011


Another thought: Give each of the blocks a "dirty bit" to symbolize falling/not falling instead of removing them from the collection.

Michael


________________________________
 From: Lars Wassermann <lars.wassermann at student.hpi.uni-potsdam.de>
To: beginners at lists.squeakfoundation.org 
Sent: Saturday, December 10, 2011 1:55 PM
Subject: Re: [Newbies] Deleting elements from a Collection while looping through it
 
Hey Jan,

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:

doFallForAllIn: aSet
     ^ aSet select: [ :block | block fall ]

Another possibility would be iterating and afterwards deleting the 
entries. But this is slower

doFallForAllIn: aSet
     aSet removeAll: (aSet reject: [ :block | block fall ])

Good luck,
Lars

Am 10.12.2011 20:43, schrieb Jan Teske:
> Hey,
>
> 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
> http://lists.squeakfoundation.org/mailman/listinfo/beginners

_______________________________________________
Beginners mailing list
Beginners at lists.squeakfoundation.org
http://lists.squeakfoundation.org/mailman/listinfo/beginners
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.squeakfoundation.org/pipermail/beginners/attachments/20111210/cca15d91/attachment.htm


More information about the Beginners mailing list