toHash /opCmp for builtin-types

Simon Buerger krox at gmx.net
Mon Feb 21 12:52:57 PST 2011


On 21.02.2011 21:22, Daniel Gibson wrote:
> Am 21.02.2011 20:59, schrieb Simon Buerger:
>> Following came to my mind while coding some generic collection classes:
>> The toHash and opCmp operations are not supported for builtin-types
>> though their implementation is trivial.
>>
>> * toHash
>> The code is already there inside TypeInfo.getHash. But
>> typeid(value).getHash(&value) is much uglier than value.toHash. Note
>> that hashes make sense for integer (trivial implementation), not
>> necessarily for floats.
>>
>> * opCmp
>> Would be useful for delegating opCmp of a struct to one member.
>> Alternative: Introduce new operator which returns 1/0/-1 (ruby does
>> this
>> with "<=>"). Currently I end up writing:
>>
>> int opCmp(...)
>> {
>> if(a>b) return +1;
>> if(a==b) return 0;
>> return -1;
>> }
>>
>> which uses 2 comparisons where only 1 is needed (though the compiler
>> might notice it if comparision is pure and so on).
>>
>> Furthermore it might me a nice idea to have toString (or the future
>> "writeTo") for builtin-types. It would need some new code in the
>> core-lib, but could simplify generic programming.
>>
>> any thoughts?
>>
>> - Krox
>
> Well, opCmp() can be done easier, at least for ints:
>
> int opCmp(...) {
> return a-b;
> }

sadly no: (-3000000000) - (3000000000) = -170532704 which is 
incorrect. It does however work for short/byte (and opCmp still 
returning int).

> For floats.. well, if you don't want/need any tolerance this would
> work as well, else it'd be more difficult.

I'm not sure if it make sense for floats. Furthermore, does 
TypeInfo.getHash support them?

> A <=> operator would be neat, though.



More information about the Digitalmars-d mailing list