2017-02-18 37 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

相關問題