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 16:56:12 PST 2017


On Wed, Feb 22, 2017 at 12:38:47AM +0000, Chad Joan via Digitalmars-d-learn wrote:
[...]

Hmm. It's actually not necessary to manually write a foreach loop to
convert an array to an AA. We could, instead, change parseTwoColumnCsv()
to return an array of std.typecons.Tuple instead (which, incidentally,
means you can elide that foreach loop too!), then there's this handy
function std.array.assocArray that will do the transcription for us,
as follows.

(In fact, you can merge AA's without ever needing to write `foreach` at
all! See below.)

---
pure private auto parseTwoColumnCsv(string inputCsv)
{
	import std.csv;
	import std.typecons;
	return csvReader!(Tuple!(string,string))(inputCsv);
}

immutable string[string] dataLookup;
immutable string[string] dataLookup1;
immutable string[string] dataLookup2;

static this()
{
	import std.array : assocArray;
	import std.range : chain;

	// Force CTFE
	immutable tuples1 = parseTwoColumnCsv("some_data1.csv");
	immutable tuples2 = parseTwoColumnCsv("some_data2.csv");

	dataLookup1 = tuples1.assocArray;	// Bam! :-P
	dataLookup2 = tuples2.assocArray;	// Bam! :-P

	// Bam, bam! - merge AA's in a single step!
	dataLookup3 = chain(tuples1, tuples2).assocArray;
}
---


T

-- 
You have to expect the unexpected. -- RL


More information about the Digitalmars-d-learn mailing list