我正试图遵循D应用程序在不同地方给出的示例。一般来说,当我学习一种语言时,我会从示例应用程序开始,并自己更改它们,纯粹是为了测试东西。
一个吸引我眼球的应用程序是计算输入文本块中单词的频率。由于字典建立在一个关联数组中(元素存储频率,键本身就是单词),所以输出没有任何特定的顺序。因此,我尝试根据站点上给出的示例对数组进行排序。
无论如何,该示例显示了lambda类型!(…)(array);'但是当我尝试代码时,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]);
}
}
当我试图编译这段代码时,我得到了以下信息
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,所以我不能评论它是否支持上面的代码。