Associative arrays in D and default comparators

xs0 xs0 at xs0.com
Fri Sep 8 05:26:46 PDT 2006


Walter Bright wrote:
> Ivan Senji wrote:
>> Yes: here is a suggestion: remove opCmp from Object. I think the only 
>> reason it is there is that when AAs where first implemented templates 
>> weren't where they are now so there was no way to check if an object 
>> has opCmp. These days a template version of AAs would be much better, 
>> and it would (if I'm not mistaken) remove the need for opCmp to be in 
>> Object.
> 
> While it'd be fun to offer a templated version of AAs, I feel the core 
> capabilities should be available to the user without needing templates. 
> This is because many programmers are not comfortable with them.

But if you hide the implementation via AA syntax sugar, those many 
programmers won't have to deal with templates at all?

> Can you give an example of a class that could not have a meaningful 
> opCmp implementation that one would want to put into an AA?

Object :)

OK, that may be a bit Java-ish, but the simplest way to obtain a unique 
key/identifier is simply "new Object()". It works in HashMaps, is equal 
only to itself, and that's about everything you need in some cases.

----

I think opCmp should be removed from Object, it causes nothing but grief:
- it errors at runtime if not implemented, instead of at compile time
- it requires you to cast the parameter
- can never be inlined

Further, I think toHash should also be removed from Object, because the 
current implementation is buggy wrt compacting GCs, and as Object has no 
inherent data except its possibly changing address, a correct default 
toHash can only return 0 (or another constant), making it useless 
(alternatively, we could acknowledge that a compacting GC for a systems 
language is practically impossible to do and stop calling the current 
implementation buggy).

Then, a templated version of AAs can check for existence of those two 
functions and implements itself accordingly. Worst case is obviously 
just a list/array of key/value pairs with linear scanning on lookup, but

- at least it works
- can be still useful/fast enough for maps with only a few keys

----

BTW, is there any particular reason for hash_t? I think it would be 
better to use uint and make it non-platform-dependent (the latter is 
bad, and the extra 32 bits don't help at all in any realistic case)


xs0



More information about the Digitalmars-d-bugs mailing list