문제

D 앱의 다양한 장소에서 제공되는 예제를 따르려고합니다. 일반적으로 언어를 학습 할 때는 예를 들어 앱에서 시작하여 직접 변경하여 순전히 테스트를 테스트합니다.

내 시선을 사로 잡은 앱 중 하나는 텍스트 블록에 단어의 주파수를 세는 것이 었습니다. 사전이 연관 배열 (요소가 주파수를 저장하는 요소와 키가 단어 자체)에 구축됨에 따라 출력 특정 순서가 아니 었습니다. 그래서 사이트에 제공된 예제를 기반으로 배열을 정렬하려고 시도했습니다.

어쨌든, 그 예는 lambda 'sort! (...) (배열)를 보여주었습니다.' 그러나 코드를 시도 할 때 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을보기 시작했기 때문에 위의 코드를 뒷받침하는지 여부에 대해서는 언급 할 수 없습니다.

도움이 되었습니까?

해결책

파일 상단 근처에 이것을 추가하십시오.

import std.algorithm;

다른 팁

다음은 입력 파일 (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 년 후 ... :-)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top