How do I use CTFE to generate an immutable associative array at compile time?
Chad Joan via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Feb 21 13:53:23 PST 2017
Hello all,
I'm trying to make this work:
---
pure string[string] parseTwoColumnCsv(string inputCsv)
{
import std.csv;
import std.typecons;
string[string] result;
foreach ( record; csvReader!(Tuple!(string,string))(inputCsv) )
result[record[0]] = record[1];
return result;
}
immutable string[string] dataLookup =
parseTwoColumnCsv(import("some_data.csv"));
void main()
{
import std.stdio;
writefln("dataLookup = %s", dataLookup);
}
---
But (with DMD 2.073.1) I am getting this error:
main.d(14): Error: non-constant expression [['a', 'b', 'c']:['x',
'y', 'z'], ['1', '2', '3']:['4', '5', '6']]
The case with normal (non-associative) arrays seems to work fine,
but is not what I needed:
---
pure string[][] parseTwoColumnCsv(string inputCsv)
{
import std.csv;
import std.typecons;
string[][] result;
foreach ( record; csvReader!(Tuple!(string,string))(inputCsv) )
result ~= [record[0],record[1]];
return result;
}
immutable string[][] dataLookup =
parseTwoColumnCsv(import("some_data.csv"));
void main()
{
import std.stdio;
writefln("dataLookup = %s", dataLookup);
}
---
Any idea how I can get this working?
I have tried a couple other things, like having the
parseTwoColumnCsv function return an immutable string[string] and
casting 'result' to that in the return statement, and I also
tried just casting the value returned from parseTwoColumnCsv as
it appears in the declaration of 'dataLookup'. I tried
std.exception's assumeUnique, but the function/template signature
doesn't seem to support associative arrays.
Thanks.
More information about the Digitalmars-d-learn
mailing list