associative arrays: iteration is finally here

Nick Sabalausky a at a.a
Thu Oct 29 17:23:09 PDT 2009


"bearophile" <bearophileHUGS at lycos.com> wrote in message 
news:hca087$dvm$1 at digitalmars.com...
> Andrei Alexandrescu:
>
>> That is debatable as it would make the same code do different things for
>> e.g. vectors and sparse vectors.
>
> Iterating on the keys is more useful, in real-world programs.
>

If you mean because it's trivial to get a value given just the key, but 
not-so-trivial the other way around, then the same argument could be made 
for regular arrays. In fact, IIRC, Haxe does just that. But I find that to 
be more of a pain than just adding that second iteration variable whenever I 
actually do need the index/key.

> Regarding the names:
> - "keys", "values" return lazy iterators. "keys" returns a set-like object 
> that supports an O(1) opIn_r (and eventually few other basic set 
> operations).
> - "items" returns a lazy iterator of Tuple(key, value) (structs, then). 
> This may also be named "pairs".
> - "allkeys", "allvalues", "allitems"/"allpairs" return arrays of 
> items/vales/Tuple.
>
> If you want to keep the API small you can even omit "allkeys", 
> "allvalues", "allitems" (so you need to do array(aa.keys) if you want them 
> all.

This is pretty much what I had in mind as well.

On the second bullet point, my vote goes for "pairs". In many contexts (like 
.NET, I think?) "item" is often used to refer to just a value, which could 
be potentially confusing.

And I think I'd prefer to omit the "all*" stuff, partly because under that 
scheme "keys"/"values" return ranges that *also* cover "all" the elements, 
which would be confusing, and also partly in hope of member-call-syntax 
eventually being extended to all types instead of just arrays so it could 
then become a nice clean "aa.keys.array". But if there's a performance issue 
with that, then maybe just something more like "aa.arraykeys" or 
"aa.eagerkeys".





More information about the Digitalmars-d mailing list