Associative arrays in D and default comparators

Bruno Medeiros brunodomedeiros+spam at com.gmail
Sat Sep 23 11:28:32 PDT 2006


Ivan Senji wrote:
> 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.
> 
> I didn't mean change int[char[]] to AA!(int, char[]),
> I meant it would be nice to change the implementation to a template, 
> without changing the syntax.
> 
> I guess this is one thing in D I still can't get over the C++ way.
> (a couple of years back I thought iostream and <<, >> where the best :)
> But these AAs and their requirements are bugging me: Why do I have to 
> (in my class ABC) declare opCmp to be int opCmp(Object o)?
> IMO that sucks because when used in an AA it's not like there is going 
> to be objects of different types as keys.
> 
> And that is a textbook example of when a template should be used.
> 
> 
>>
>> 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?
> 
> Sean Kelly gave a good example.
> 
> But I have nothing against AAs requiring opCmp, opEquals, toHash or what 
> ever it needs, but would prefer for them not to be in Object.

This is not an issue I know a lot about, but that seems a good idea.
For the record, both Java and C# have an Equals and a Hash method in the 
Object class, but the Compare method is not. Classes that are comparable 
implement the IComparable interface, which is a generic interface since 
the introduction of generics, meaning that the Compare method parameter 
does not have to be of type Object, like in D.
(Note: of course, in D an interface wouldn't be needed, an 
under-the-hoods templated AA implementation can simply check if the 
opCmp method exists or not, in what is effectively a compile-time 
version of duck-typing)


-- 
Bruno Medeiros - MSc in CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list