在D语言中基于关联数组的排序

7

我试图学习D语言,参考了各种例子。通常来说,当我学一门新语言时,我会从示例应用程序开始,并对其进行更改,以纯粹测试这些东西。

有一个应用程序引起了我的注意,它可以计算传入文本块中单词的频率。由于字典是在关联数组中建立的(元素存储频率,键为单词本身),因此输出不是按任何特定顺序排列的。所以,我尝试根据网站上提供的示例对数组进行排序。

无论如何,该示例展示了一个lambda 'sort!(...)(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): 错误: 未定义的标识符 sort
s1.d(24): 错误: 函数期望 () 前面的函数,而不是 int 类型的 sort
请问有人能告诉我需要做什么吗?
我使用的是 DMD v2.031,我尝试安装了 gdc,但它似乎只支持 v1 语言规范。我刚开始接触 dil,所以无法评论它是否支持上述代码。

1
GDC 已经不太活跃了,基于 LLVM 的 LDC 已经取代了它的位置。 - BCS
2个回答

11

尝试在文件顶部添加以下内容:

import std.algorithm;

1
糟糕!谢谢,它有效。总是那些简单的东西最难找到信息! - GKelly

2

以下是更简单的方法来获取输入文件(从命令行),获取行/单词并按降序打印单词频率表:

import std.algorithm;
import std.file;
import std.stdio;
import std.string;

void main(string[] args)
{   
    auto contents = cast(string)read(args[1]);
    uint[string] freqs;

    foreach(i,line; splitLines(contents))
        foreach(word; split(strip(line)))
            ++freqs[word];

    string[] words = freqs.keys;
    sort!((a,b)=> freqs[a]>freqs[b])(words);

    foreach(s;words) 
        writefln("%s\t\t%s",s,freqs[s]);
}

四年后,时间过得真快... :-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接