On Tuesday, 19 March 2013 at 21:11:12 UTC, Jonathan M Davis wrote:
Lots of stuff uses ==, toHash, etc. That's the way the language is designed.

Agreed

Defining your types without defining those properly just isn't going to work for a _lot_ of stuff. Creating an external function to compare objects or generate hashes or anything like that is just going to cause problems, because only
your stuff would use it.

Ok - you are making strong statement and I don't see why it is the case.

Here is an example that does work for hashing.
Note: R implements its own hash and just prints to show nothing up the sleeve. Other classes (S,T) have no toHash implemented directly at all - yet you can see u1 and u3 resolve to the same hash and u2 a different, as you would expect.

-------------------------
import std.stdio;
import opmix.mix;
import pprint.pp;

struct R {
  string r;
  hash_t toHash() const nothrow {
    try {
      writeln("toHash called on r");
    } catch(Exception) {
    }
    return typeid(string).getHash(&r);
  }
}

struct S {
  R r;
  string s;
  string[int] si;
}

struct T {
  S s;
}

struct U {
  mixin ToHash;
  T t;
}

void main() {
  U u1 = U(T(S(R("a"), "foo", [1:"goo"])));
  U u2 = U(T(S(R("a"), "foo".idup)));
  U u3 = U(T(S(R("a"), "foo".idup, [1:"goo".idup])));

  writeln(deepHash(u1));
  writeln(deepHash(u2));
  writeln(deepHash(u3));

  writeln(pp(u1));

  int[U] aa;
  aa[u1] = 100;
  writeln("Is u1 in aa ", u1 in aa);
  writeln("Is u2 in aa ", u2 in aa);
  aa[u2] = 100;
  writeln("Is u2 in now aa ", u2 in aa);

}

----------------------- OUTPUT --------------------------
toHash called on r
614624
toHash called on r
582446
toHash called on r
614624
{
 (U).t = {
  (T).s = {
   (S).r = {
    (R).r = "a"
   }
   (S).s = "foo"
   (S).si = {
    (K(1)[0] =>
     V("goo")),
   }
  }
 }
}
toHash called on r
toHash called on r
Is u1 in aa 7F2C7E556FC0
toHash called on r
Is u2 in aa null
toHash called on r
toHash called on r
Is u2 in now aa 7F2C7E556F40
----------------------------------------------------------------------


The built-in stuff wouldn't, and the standard library
wouldn't. For instance, AAs require that opEquals and toHash be defined, and no matter how clever your external functions for comparing objects or generating hashes are, they're not going to work with the built-in AAs. Any type which is going to work with the built-in AAs must define opEquals and toHash.


The above works with the built-in AAs.
Please offer an example.

Thanks
Dan

Reply via email to