a sets implementation

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Wed Feb 7 04:18:47 PST 2007


Stephan Diehl wrote:
> Michiel wrote:
>> * I would overload the 'in' operator anyway.
> 
> I tried. But for some reason, the compiler insists on associative arrays 
> when using the 'in' operator. And when used with associative arrays, it 
> will test the values, not the keys. (it's just the other way round in 
> python: the 'in' operator checks for the keys, which actually does make 
> some sense).

??
I think you're a bit confused here. When used with associative arrays 
the 'in' operator definitely tests keys, not values[1]. For associative 
arrays it may return a pointer to the value, but it checks if the key is 
in the AA.
Or did you mean you expect it to return the key? Why would you want 
that? You already know what the key is or you couldn't have determined 
it was in the AA in the first place.

A common idiom for associative array member testing in D is:
---
if (auto p = key in aa) {
     // 'aa' contains 'key', and associates it with value '*p'
} else {
     // 'aa' does not contain key
}
---
The idea is that after determining a key is present in an associative 
array the next thing you'll probably want to have is the value 
associated with it.


A note about overloading: If you want to overload the 'in' operator 
you'll probably want to use opIn_r (so that it's used for "key in set" 
expressions), not opIn (which would give you "set in key" syntax, which 
doesn't make much sense).



More information about the Digitalmars-d mailing list