www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Re: Revamping associative arrays

Moritz Warning:

 foreach(key; aa.keys)

It's undefined behavior. You shouldn't try to mutate the aa while iterating. I hope that will be fixed. It took me some time to find this out.

In Python:
 d = {1:2, 3:4}
 for k in d: del d[k]

Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: dictionary changed size during iteration The "for k in d" sets a flag inside the d dict (AA), and del and insert operations test this flag, if it's true a runtime exception is thrown. Something like this is enough in Python, but I think in D it's not safe enough and it may be a little slow too (because you have to test a flag every time). In D a compile-time test pass may be able to catch and warn against most of such situations (lint tools are able to do far more complex things). -------------------- Christopher Wright
Why not mandate using both keys and values?<

Iterating on tuples of an AA is probably a little slower than iterating on just keys. On the other hand such AAs will have something like xkeys and xvalues methods too, that return light iterable objects (ranges, the first one has a O(1) opIn_r, while the opIn_r of the second is O(n)) that are enough to regain the lost performance when you need only keys or values, so this situation can become acceptable. Bye, bearophile
Oct 19 2009