代码之家  ›  专栏  ›  技术社区  ›  GKelly

基于D中关联数组的排序

dmd d
  •  7
  • GKelly  · 技术社区  · 16 年前

    我正试图遵循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,所以我不能评论它是否支持上面的代码。

    2 回复  |  直到 12 年前
        1
  •  11
  •   DK.    16 年前

    尝试在文件顶部附近添加:

    import std.algorithm;
    
        2
  •  2
  •   Dr.Kameleon    12 年前

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

    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年后…-)

    推荐文章