Bug 10046 – Wrong insertion of Tuple in associative array
Status
RESOLVED
Resolution
DUPLICATE
Severity
normal
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2013-05-08T04:39:00Z
Last change time
2014-07-04T17:37:10Z
Assigned to
nobody
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2013-05-08T04:39:02Z
import std.stdio: writeln;
import std.typecons: Tuple;
void main () {
alias Foo = Tuple!string;
int[Foo] aa;
auto ka = Foo("foo".idup);
aa[ka] = 1;
auto kb = Foo("foo".idup);
aa[kb] = 2;
aa.writeln;
}
Output dmd 2.063beta:
[Tuple!(string)("foo"):1, Tuple!(string)("foo"):2]
Expected output:
[Tuple!(string)("foo"):2]
Comment #1 by joanbrugueram — 2013-10-27T11:25:25Z
Very annoying bug since it basically kills "multiindexing" using associative arrays. As far as I know it's simply because Tuple hasn't implemented toHash.
It can be worked around by using an structure with a toHash function (WARNING: The documentation on associative arrays says it's called opHash. It's called toHash!).
Here's my drop-in replacement for 2-tuples. Feel free to use it freely for whatever you want. It works in my (string, string) case but I haven't tested it for other types, but it should work.
****
// Workaround for http://d.puremagic.com/issues/show_bug.cgi?id=10046
static struct MyTuple(A, B)
{
private A first;
private B second;
auto ref opIndex(size_t index)
{
switch (index)
{
case 0: return first;
case 1: return second;
default: assert(0);
}
}
const hash_t toHash()
{
return typeid(A).getHash(&first) ^ typeid(B).getHash(&second);
}
const bool opEquals(ref const MyTuple!(A, B) s)
{
return first == s.first && second == s.second;
}
const int opCmp(ref const MyTuple!(A, B) s)
{
if (first != s.first)
return (first < s.first) ? -1 : 1;
if (second != s.second)
return (second < s.second) ? -1 : 1;
return 0;
}
}
Comment #2 by jens.k.mueller — 2014-02-17T01:29:09Z
To rephrase more drastically: std.typecons.Tuple is incompatible with associative arrays because it does not implement toHash and opCmp.
Comment #3 by andrej.mitrovich — 2014-04-26T14:18:42Z
Can we get a pull for this?
Comment #4 by k.hara.pg — 2014-07-04T17:37:10Z
*** This issue has been marked as a duplicate of issue 11037 ***