How do I use CTFE to generate an immutable associative array at compile time?

Daniel Kozak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 21 14:50:02 PST 2017


I have similar issue and I beleive I was able to workaround that 
somehow, but it is so many years now :(. Have you tried enum dataLookup 
instead of immutable string[string] dataLookup


Dne 21.2.2017 v 22:53 Chad Joan via Digitalmars-d-learn napsal(a):
> 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