拥有以下代码:
import std.algorithm : filter, canFind, map, splitter, group, sort;
import std.stdio : File, writefln;
import std.range : array;
void main(string[] args)
{
string filename = "/var/log/dpkg.log";
string term = args[1];
auto results = File(filename, "r")
.byLine
.filter!(a => canFind(a, term))
.map!(a => splitter(a, ":").front)
.group
.array // why is this crucial ?
.sort!((a,b) => a[1] > b[1]);
foreach (line; results)
writefln("%s => %s times", line[0], line[1]);
}
我发现在.array
之后我迫切需要.group
。谁能告诉我为什么会这样?
一旦我摆脱它,我得到以下编译器错误:
main.d(16): Error: template std.algorithm.sorting.sort cannot deduce function from argument types !((a, b) => a[1] > b[1])(Group!("a == b", MapResult!(__lambda3, FilterResult!(__lambda2, ByLine!(char, char))))), candidates are:
/usr/include/dmd/phobos/std/algorithm/sorting.d(1830): std.algorithm.sorting.sort(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range)(Range r) if ((ss == SwapStrategy.unstable && (hasSwappableElements!Range || hasAssignableElements!Range) || ss != SwapStrategy.unstable && hasAssignableElements!Range) && isRandomAccessRange!Range && hasSlicing!Range && hasLength!Range)
答案 0 :(得分:7)
group
的结果是一个延迟评估的序列,但sort
要求其完整输入完全在内存中,例如数组。 array
函数采用group
生成的延迟序列,并将其存储到sort
能够处理的数组中。