我在rosettacode.org上发布了以下代码,用于converting Arabic and Roman numerals的任务。D2:std.algorithm.indexOf不再工作
import std.regex, std.array, std.algorithm;
immutable {
int[] weights = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
string[] symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX",
"V", "IV", "I"];
}
string toRoman(int n) {
auto app = appender!string;
foreach (i, w; weights) {
while (n >= w) {
app.put(symbols[i]);
n -= w;
}
if (n == 0) break;
}
return app.data;
}
int toArabic(string s) {
int arabic;
foreach (m; match(s, "CM|CD|XC|XL|IX|IV|[MDCLXVI]")) {
arabic += weights[symbols.indexOf(m.hit)];
}
return arabic;
}
它曾经工作得很好,但现在我得到一个编译器错误。
Error: template std.algorithm.indexOf(alias pred = "a == b",R1,R2) if (is(typeof(startsWith!(pred)(haystack,needl e)))) does not match any function template declaration
根据文档indexOf已弃用,应使用countUntil替代,但它给了我同样的错误。
我明白了。有没有办法获得一个元素的索引在一个不可变的集合中,还是我应该封装这些数组,让它们变成私有的,创建访问器并滚动我自己的indexOf? – fwend 2011-03-31 14:09:08
@fwend:现在最简单的方法是将其转换为可变头。例如:'immutable(string)[] headMutable = symbols;',然后做'headMutable'而不是'symbols'。 – dsimcha 2011-03-31 14:28:48
你知道任何解决这个问题的建议吗?不能在不可变数组上使用'indexOf'是一个相当大的问题。 – 2011-03-31 23:58:54