AA key conversion woes

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Apr 19 12:32:30 PDT 2012


On Wed, Apr 18, 2012 at 04:02:05PM +0200, Somedude wrote:
[...]
> I'm not sure I understood the whole issue and its implications, but
> would this work: a map template that takes any parameter T as key AND
> a lambda/anonymous/delegate function as a hash function ? Unlike Java,
> passing the hash function avoids having to define a hashCode() and
> equals() method for each class.

In my mind, such a thing would belong to std.container. The built-in
AA's should be as straightforward as possible, that is, given any
reasonable key type, it should do the "right thing".

Also, it's not hard to use UFCS to make a default toHash() function for
classes that uses some default hashing algorithm on any class (same
thing applies to structs) so that you don't have to define them per
class unless you wish to override the default hash function.


> We don't impose any restraint on T, .keys would simply return T[], e.g
> if T is immutable(int), .keys would be immutable(int)[].
> I don't see the necessity for .keys itself to be an immutable array. I
> even think it would be counter productive.

Believe me, I would rather not have immutable keys if I could help it,
because it makes things so much simpler. However:

(1) It leads to subtle breakages due to unintended aliasing:

	int[int[]] aa;
	int[] key1 = [1,2,3];
	aa[key1] = 123;
	key1[0] = 2;	// uh oh!
	assert(aa[[1,2,3]] == 123);	// assertion fails, key has
					// changed without AA's knowledge

(2) It tickles some compiler bugs/language ambiguities that causes
things like this to not work as expected:

	int[char[]] aa;
	aa["abc"] = 123;	// compile error: cannot convert string to char[]
	const(char)[] key1 = "abc";	// works
	aa[key1] = 123;		// compile error: cannot convert const(char)[] to char[]

Having immutable keys (or at least const keys) allows the AA
implementation to specify const(keytype) in opIndex's parameters, so
that you can pass in char[], const(char)[], or string, and it will work
as expected.

As for .keys, I agree that it should not be an immutable array, it just
needs to be tail-immutable (its elements are immutable, but the array
can be changed).


T

-- 
We are in class, we are supposed to be learning, we have a teacher... Is it too much that I expect him to teach me??? -- RL


More information about the Digitalmars-d mailing list