Is it possible to add items to the arrays and hashes at compile time?

Dennis Ritchie via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 9 18:53:15 PDT 2015


On Sunday, 7 June 2015 at 15:20:17 UTC, Ali Çehreli wrote:
> /* Some function that generates an AA */

Thanks. Beautiful code, but I want a little more :)

/* Some function that generates an AA */
int[][int][int] initHash(int i)
{
	/* It is nice to see that this function is not called at run 
time */
	if (!__ctfe) {
		import std.stdio;
		writefln("%s is called at run time", __FUNCTION__);
	}
	
	return [i : [ i : [i, i] ] ];
}

/* Question: Is there a function to merge two AAs? */
int[][int][int] merge(Hash)(Hash[] hashes...)
{
	/* It is nice to see that this function is not called at run 
time */
	if (!__ctfe) {
		import std.stdio;
		writefln("%s is called at run time", __FUNCTION__);
	}
	
	int[][int][int] result;
	
	foreach (hash; hashes) {
		foreach (key, value; hash) {
			result[key] = value;
		}
	}
	
	return result;
}

/* These three are generated at compile time */
enum firstPart = initHash(1);
enum secondPart = initHash(2);
enum int[][int][int] ctHash = merge(firstPart, secondPart);

void main()
{
	import std.stdio;

	static if (!(4 in ctHash)) {{
		// ...
	}}

	ctHash[4][4] ~= [4, 4]; // I want this to work at compile time :)
	// Possible?

	static if (!!(4 in ctHash)) {{
		// ...
	}}
}


More information about the Digitalmars-d-learn mailing list