2017-02-18 38 views
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) 
+0

请注意,“group”也取决于排序:将__consecutively__等同元素分组为元素的单个元组及其重复次数。 [见文档](https://dlang.org/phobos/std_algorithm_iteration.html#.group) – greenify

回答

7

group结果是懒洋洋地评估序列,但sort要求其全部投入完全在内存中,例如数组。 array函数采用由group生成的惰性序列,并将其存储到数组中,该数组可以对其执行操作。

+0

太棒了!这正是我想要的。 – Patryk

相关问题