问题
My plan is to write a mutation-less code in D-language so that my values are available by runtime. Someone spoke to me about loop-unrolling and compile time code generation but I have no clear idea how to do that. I have made the D-template below but it has no guarantee to be evaluated at compile-time because on the two assignment statements(mutations) . Advice would be greatly appreciated. Suggestions could be 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 the pattern to be 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);
}
回答1:
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 - i - 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]
Code on dpaste.
来源:https://stackoverflow.com/questions/31781188/removing-mutations-for-d-metaprogramming-compiletime-array-generation