2009-08-11 101 views
7

我试图按照D应用程序在各个地方给出的示例。通常,在学习语言时,我从示例应用程序开始,自己更改它们,纯粹是为了测试东西。基于D中的关联数组排序基于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): Error: undefined identifier sort 
    s1.d(24): Error: function expected before(), not sort of type int 

谁能告诉我什么,我需要在这里做什么?

我使用DMD v2.031,我试过安装gdc,但这似乎只支持v1语言规范。我只开始考虑dil,所以我不能评论这是否支持上面的代码。

+1

GDC是那种死的,基于LLVM公司已采取我t的地方。 – BCS 2009-08-11 16:55:24

回答

11

尝试增加此接近文件的顶部:

import std.algorithm; 
+1

Doh!谢谢,这是有效的。它总是最简单的东西,最难找到的信息! – GKelly 2009-08-13 10:35:02

2

这里有一个更简单的方法来获得的输入文件(从CMDLINE),获得线/字和打印字frequencing的表,按降序顺序:

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]); 
} 

好,近4年后... :-)