本文介绍了删除D元编程/编译时数组生成的突变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的计划是用D语言编写一个无变异的代码,以便我的值在运行时可用.有人跟我谈到了循环展开和编译时代码生成的问题,但我不清楚如何做到这一点.我在下面做了D模板,但是不能保证在编译时会进行评估,因为这是在两个赋值语句(突变)上进行的.建议将不胜感激.建议最好是在没有宏的D或C ++中使用.
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);
}
推荐答案
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);
}
输出:
['A':0, 'B':1, 'C':3, 'D':3, 'F':3, 'G':3, 'H':3, 'R':3, 'S':3, 'T':3]
这篇关于删除D元编程/编译时数组生成的突变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!