d - 基于 D 中的关联数组排序

标签 d dmd

我正在尝试遵循 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):错误:未定义的标识符排序
s1.d(24): 错误:() 之前预期的函数,不是 int 类型

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

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

最佳答案

尝试将其添加到文件顶部附近:

import std.algorithm;

关于d - 基于 D 中的关联数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1259448/

相关文章:

assembly - DMD 堆栈跟踪中的地址有何含义?

compiler-construction - 使用 rebuild 和 drebuild 编译带有 .d 扩展名的代码?

d - 实例化 redBlackTree 模板时出错

d - contracts.d 无法读取

curl - D etc.c.curl 示例

linux - Linux 中的 std.net.curl 链接器错误

string - d编程,将字符串解析或转换为 double

D2 : switch statement and variables

用 D 解析文件

Dlang byLine复制跳行