2009-08-11 94 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年後... :-)