Deletion iterators

Often, deleting during iteration is problematic. So, in say Python, if you write:


for e in edges:
    if seen(e.v1) or seen(e.v2):
        delete e


you are in for some trouble.

And this is understandable. The default iterator is meant to get you through a sequence rapidly, and no one wants to drag along the baggage that would allow you to muck about with the sequence as you traverse it.

But why not have a second type of iterator that does allow deletion, which you would pull out just for the special cases where the above code is the sort of thing you need to do? Because I've had to "hand-roll" one of these every few months, it seems, and I bet others have as well.

Java has something like this with "fail-safe" iterators, but they seem to be for protection from another thread modifying the data while you iterate. In fact, the fail-safe iterator is guaranteed not to change while you are iterating.

Comments

  1. Look ahead one step.
    Alternatively, use an immutable collection but build a new winnowed collection. Unless there's some serious performance issue that approach will save you a lot of grief in the long run.

    ReplyDelete
  2. Btw, I recall the C++ STL having a variety of iterators for a variety of purposes.

    ReplyDelete

Post a Comment

Popular posts from this blog

Libertarians, My Libertarians!

"Machine Learning"

"Pre-Galilean" Foolishness