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

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 21 14:43:15 PST 2017


On Tue, Feb 21, 2017 at 10:34:57PM +0000, Chad Joan via Digitalmars-d-learn wrote:
> On Tuesday, 21 February 2017 at 22:26:01 UTC, Chad Joan wrote:
> > On Tuesday, 21 February 2017 at 21:58:07 UTC, Stefan Koch wrote:
> > > On Tuesday, 21 February 2017 at 21:53:23 UTC, Chad Joan wrote:
> > > > Hello all,
> > > > 
> > > > I'm trying to make this work:
> > > > 
> > > > [...]
> > > 
> > > You cannot create AA's at ctfe and carry them over to runtime use.
> > > You'd have to use a costum dictionary-type.
> > > I think the vibe.d project has one you could use.
> > 
> > I wondered if this might be the case.
> > 
> > Well, I won't worry about it then.  I'll have to find another way
> > around.
> > 
> > Thanks a bunch!
> 
> For the sake of the rest of the internet, here is what I'm probably going to
> stick with:
> 
> ---
> 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;
> 
> static this()
> {
> 	dataLookup = parseTwoColumnCsv(import("some_data.csv"));
> }
> 
> void main()
> {
> 	import std.stdio;
> 	writefln("dataLookup = %s", dataLookup);
> }
> ---
> 
> In this case the AA isn't actually coded into the executable; but at least
> the configuration from some_data.csv will be in the executable as a string.
> The program will construct the AA at startup.  It's not as "cool", but it
> should get the job done.
[...]

Parsing strings at program startup is ugly and slow.  What about parsing
at compile-time with CTFE into an array literal and transforming that
into an AA at startup, which should be a lot faster?

	// Warning: untested code
	pure string[2][] parseTwoColumnCsv(string inputCsv)
	{
		import std.csv;
		import std.typecons;

		string[2][] result;
		foreach (record; csvReader!(Tuple!(string,string))(inputCsv)) {
			result ~= [record[0], record[1]];
		}
		return result;
	}

	immutable string[string] dataLookup;
	static this()
	{
		enum halfCookedData = parseTwoColumnCsv(import("some_data.csv"));
		foreach (p; halfCookedData) {
			dataLookup[p[0]] = p[1];
		}
	}


T

-- 
Those who've learned LaTeX swear by it. Those who are learning LaTeX swear at it. -- Pete Bleackley


More information about the Digitalmars-d-learn mailing list