On Tuesday, 20 May 2014 at 20:15:09 UTC, Dominikus Dittes Scherkl
wrote:
/// create a fixed size array with the given name and with *max* entries

max + 1 entries

/// of immutable values of the same type as the return value of the
/// given function.
/// it contains the values of that function in the range [0..max]. string makeLookupTable(alias fn, uint max=255)(string name) pure @safe if(is(typeof(fn(max))))
{
string table = "immutable " ~ to!string(typeof(fn(max))) ~ "[" ~ to!string(max+1) ~ "] " ~ name ~"= [ ";
   foreach(i; 0..max) table ~= to!string(fn(i) ~ ", ";
   return table ~ to!string(fn(max) ~" ]";
}

Couldn't resist purging that of the string fiddling:

private template staticIota(uint n)
{
     import std.typetuple: TypeTuple;
     static if(n == 0) alias staticIota = TypeTuple!();
     else alias staticIota = TypeTuple!(.staticIota!(n - 1), n -
1);
}

template lookupTable(alias fn, uint max = 255)
{
     import std.traits: ReturnType;
     import std.typetuple: staticMap;
     static assert(max < uint.max);
     enum length = max + 1;
     enum ctfn(uint x) = fn(x);
     alias elements = staticMap!(ctfn, staticIota!length);
     enum ReturnType!fn[length] lookupTable = [elements];
}

void main()
{
     char f(uint x) pure @safe {return x == 42 ? '!' : '.';}
     static immutable t = lookupTable!f;
     static assert(is(typeof(t) == immutable char[256]));
     assert(t[42] == '!');
}

Reply via email to