7

Dアプリのさまざまな場所で与えられた例に従おうとしています。通常、言語を学習するときは、サンプル アプリから始めて、純粋にテストするために自分で変更します。

私の目を引いたアプリの 1 つは、渡されたテキスト ブロック内の単語の頻度をカウントすることでした。辞書は連想配列 (要素は頻度を格納し、キーは単語自体) で構築されているため、出力は順不同でした。そのため、サイトで提供されている例に基づいて配列をソートしようとしました。

とにかく、例はラムダ '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): エラー: 未定義の識別子ソート
    s1.d(24): エラー: () の前に関数が必要であり、int 型の種類ではありません

ここで何をする必要があるか誰か教えてもらえますか?

DMD v2.031 を使用しています。gdc をインストールしようとしましたが、これは v1 言語仕様のみをサポートしているようです。dil を見始めたばかりなので、これが上記のコードをサポートしているかどうかについてコメントすることはできません。

4

2 に答える 2

11

これをファイルの先頭近くに追加してみてください。

import std.algorithm;
于 2009-08-11T10:38:47.517 に答える
2

入力ファイルを(cmdlineから)取得し、行/単語を取得し、単語の頻度の表を降順で出力するさらに簡単な方法を次に示します。

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年後... :-)

于 2013-02-06T13:02:31.057 に答える