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

Ali Çehreli acehreli at yahoo.com
Mon Aug 15 02:23:34 UTC 2022


On 8/14/22 18:47, johntp wrote:
 > I'm using DMD64 D Compiler v2.100.0 on linux mint.

Same version here.

 > I copied the author's
 > solution and got the same thing.

Wow! Are people actually working on those? :)

At first, I couldn't even get the code to compile due to 
const-correctness issues with opCmp. :/ I used the following cast():

   foreach (i, point; points) {
       immutable comparison = (cast()point).opCmp(rhs.points[i]);
       // ...
   }

 > Is there an errata page for the book?

No. It is supposed to be corrected as mistakes are discovered. The 
online version should be the most recent.

The bug was with trying to implement that unnatural "ignore the color" 
in the comparison logic but then toHash was taking advantage of existing 
array hashing code, which had no idea of the programmer's requirement:

class Point {
   int x;
   int y;
   Color color;

   // IGNORES COLOR:
   override bool opEquals(Object o) const {
     const rhs = cast(const Point)o;
     return rhs && (x == rhs.x) && (y == rhs.y);
   }

   // ...
}

class TriangularArea {
     // BUG DUE TO WISHFUL THINKING:
     override size_t toHash() const {
       /* Since the 'points' member is an array, we can take
        * advantage of the existing toHash algorithm for
        * array types. */
       return typeid(points).getHash(&points);
     }

     // ...
}

Here is a very inefficient implementation that still relies on existing 
array hashing functionality but after creating an array that does not 
contain the color field. I am pretty sure sort(tuples) is needed but at 
least the example works without it as well:

   override size_t toHash() const {
     auto tuples = points[].map!(p => tuple(cast()p.x, cast()p.y)).array;
     sort(tuples);
     return () @trusted {
       return typeid(tuples).getHash(&tuples);
     }();
   }

Writing it in an efficient way is left as en excercise because the 
auther is too lazy to learn how to do it. :p

In case it's not clear, toHash() creates a new array which does not 
contain any color information and then sorts it and then needs to use 
the @trusted trick because toHash is @safe (apparently).

Ali



More information about the Digitalmars-d-learn mailing list