c++11 - Removing mutations for D metaprogramming/compiletime array generation -
my plan write mutation-less code in d-language values available runtime. spoke me loop-unrolling , compile time code generation have no clear idea how that. have made d-template below has no guarantee evaluated @ compile-time because on 2 assignment statements(mutations) . advice appreciated. suggestions preferably in d or c++ without macros.
import std.stdio; import std.string; import std.conv; const char[] alphabet="abfcdfrghdsthfg"; const string pattern="aba"; i[c] computeatcompiletime(s ,c,i)( const s pattern ){ i[c] table1; const int size = to!int(pattern.length) ;//length of pattern matched foreach( c; alphabet){ //initialise array table1[c] = size; } foreach(i; 0..size-1){ table1[pattern[i]] = size -i-1; } return table1; } enum tablefromcompiler = computeatcompiletime!(const string ,char, int)(pattern); void main(){ // enum tablefromcompiler = computeatcompiletime!(const string ,char, int)(pattern); writeln(tablefromcompiler); }
import std.stdio; immutable char[] alphabet = "abfcdfrghdsthfg"; int[char] compute(in string pattern) { int[char] table; foreach (c; alphabet) { table[c] = cast(int)pattern.length; } foreach (i, c; pattern) { table[c] = cast(int)(pattern.length - - 1); } return table; } void main() { enum table = compute("aba"); writeln(table); }
output:
['a':0, 'b':1, 'c':3, 'd':3, 'f':3, 'g':3, 'h':3, 'r':3, 's':3, 't':3]
Comments
Post a Comment