2
具有下面的一段代碼:.group爲什麼在.group之後必須使用.sort?
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]);
}
我發現,我迫切需要.group
後.array
。誰能告訴我爲什麼?
一旦我擺脫它,我得到以下編譯器錯誤:
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)
請注意,「group」也取決於排序:將__consecutively__等同元素分組爲元素的單個元組及其重複次數。 [見文檔](https://dlang.org/phobos/std_algorithm_iteration.html#.group) – greenify