我试图按照D应用程序在各个地方给出的示例.通常在学习语言时,我会从示例应用程序开始并自行更改,纯粹是为了测试内容.
引起我注意的一个应用是计算传入的文本块中的单词的频率.由于字典是在关联数组中构建的(元素存储频率,键是单词本身),输出没有任何特定的顺序.因此,我尝试根据网站上给出的示例对数组进行排序.
无论如何,这个例子显示了一个lambda'排序!(...)(数组);' 但是当我尝试代码时,dmd将无法编译它.
这是简化的代码:
import std.stdio;
import std.string;
void main() {
uint[string] freqs;
freqs["the"] = 51;
freqs["programming"] = 3;
freqs["hello"] = 10;
freqs["world"] = 10;
/*...You get the point...*/
//This is the actual example given, but it doesn't
//seem to work, old D version???
//string[] words = array(freqs.keys);
//This seemed to work
string[] words = freqs.keys;
//Example given for how to sort the 'words' array based on
//external criteria (i.e. the frequency of the words from
//another array). This is the line where the compilor craps out!
sort!((a,b) {return freqs[a] < freqs[b];})(words);
//Should output in frequency order now!
foreach(word; words) {
writefln("%s -> %s", word, freqs[word]);
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译此代码时,我得到以下内容
s1.d(24): Error: undefined identifier sort
s1.d(24): Error: function expected before (), not sort of type int
谁能告诉我在这里需要做什么?
我使用DMD v2.031,我已经尝试安装gdc,但这似乎只支持v1语言规范.我只是开始关注dil,所以我无法评论这是否支持上面的代码.