www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - AA iteration with modify

This is a reduced version of a little single-thread program that uses an AA:

import std.stdio;
void main() {
  int[int] aa;
  for(int i; i < 100; i++)
    aa[i] = i;
  foreach(k, v; aa)
    if (k < 1000)
      aa.remove(k);
  writefln(aa);
}

At the end aa contains:

[97:97,98:98,99:99]

instead of being empty because the code changes the AA during the iteration.

I think D may help the programmer avoid such bugs; a very simple (and probably
fast enough) way to avoid that bug is to add a "state" long integer to the AA
struct, that is incremented whenever the AA state is modified (key added, key
deleted, etc). Then at the beginning of the OpApply of the AA you can copy
"state" in a local variable and you can raise an error if it changes during the
iteration.

This doesn't solve all problems (and it slows down a bit every operation on the
AA, because you have to increment that "state" counter) because the state of
the AA itself isn't really protected (you can put reference types in both keys
and values, so you can change that state later without touchign the "state"
variable (maybe D2.x may solve most of this problem)), but in many common
situations it may avoid that iteration bug to D newbies :-)

Bye,
bearophile
Jan 04 2008