Wednesday, February 15, 2017

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.


  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.

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


Euphemisms II

It's not just abortion where these euphemisms bug me either. I think it is sometimes OK to euthanize your pet, but... you did not "...