associative array: unexpected results after static initialization
kdevel
kdevel at vogtner.de
Sat Dec 2 01:02:22 UTC 2017
On Friday, 1 December 2017 at 17:02:48 UTC, H. S. Teoh wrote:
> [...]
> There is at least 1 use case in the bugzilla issue that
> justifies AA literals with (possibly) duplicated keys:
>
> https://issues.dlang.org/show_bug.cgi?id=15290#c1
>
> Code snippet:
> -------
> foreach (i; 0..10)
> foreach (j; 0..10) if (pred2 (i, j))
> foreach (k; 0..10) if (pred3 (i, j, k))
> ... and maybe more ...
> {
> auto set = [i: true, j: true; k: true];
> if (set.length == 3)
> {
> ... we found distinct i, j, k, ...
> }
> }
> -------
Sure. this looks "idiomatic" but the keys are not constants. If
the compiler only complained on compile-time duplicate keys it
would not do so in this case.
BTW: I was under the impression (never checked or profiled such
code) that in the following code trans_AA and trans_switch are
technically equivalent:
```
string trans_AA (string s)
{
immutable string[string] aa = [
"src1" : "repl1",
"src2" : "repl2",
"src3" : "repl3",
];
return aa[s];
}
string trans_switch (string s)
{
switch (s) {
case "src1": return "repl1";
case "src2": return "repl2";
case "src3": return "repl3";
// case "src3": return "repl3";
default:
throw new Exception ("no key " ~ s);
}
}
void main ()
{
import std.stdio;
import std.string;
auto a = stdin.readln.chomp;
a.trans_switch.writeln;
a.trans_AA.writeln;
}
```
If one uncomments the "src3" line in trans_switch the compiler
complains with
aa.d(17): Error: duplicate case "src3" in switch statement
while a duplication in trans_AA goes unnoticed.
More information about the Digitalmars-d-learn
mailing list