Exercise at end of Ch. 56 of "Programming in D"

Paul Backus snarwin at gmail.com
Sat Aug 20 21:26:25 UTC 2022


On Monday, 15 August 2022 at 02:59:59 UTC, Ali Çehreli wrote:
> class Point {
>   int x;
>   int y;
>   Color color;
>
>   // ...
>
>   override size_t toHash() const {
>     return x + y;
>   }
> }
>
> The book is simply forgetting to show that function. 
> (Otherwise, I never put any code without testing.)
>
> WARNING: Hash functions can be very tricky. I have a strong 
> feeling that adding two integers is not an efficient one.

Fortunately there is no need to invent our own hash function 
here, because we can use the generic hashOf [1] from druntime:

     override size_t toHash() const {
         return hashOf(y, hashOf(x));
     }

The second argument is optional, and is used when you want to 
"accumulate" a single hash value from multiple input values.

[1] https://druntime.dpldocs.info/object.hashOf.1.html


More information about the Digitalmars-d-learn mailing list