代码之家  ›  专栏  ›  技术社区  ›  rnso

为什么过滤器不能处理字符串列表

  •  0
  • rnso  · 技术社区  · 7 年前

    我正在尝试编写代码来读取文本文件并过滤掉包含两个搜索项的行:

    import std.stdio;
    import std.string; 
    import std.file : readText;
    import std.algorithm; 
    
    void main(){
        string[] srchitems = ["second", "pen"];  // to search file text for lines which have both these; 
        auto alltext = readText("testing.txt");
        auto alllist = alltext.split("\n");  
        foreach(str; srchitems){
            alllist = alllist.filter!(a => a.indexOf(str) >= 0);    // not working ;
        }
        writeln(alllist); 
    }
    

    但是,它不工作,并出现以下错误:

    $ rdmd soq_filter.d 
    soq_filter.d(11): Error: cannot implicitly convert expression filter(alllist) of type FilterResult!(__lambda1, string[]) to string[]
    Failed: ["/usr/bin/dmd", "-v", "-o-", "soq_filter.d", "-I."]
    

    以下带有cast的行也不起作用:

        alllist = cast(string[]) alllist.filter!(a => a.indexOf(str) >= 0);     // not working ;
    

    Error: cannot cast expression filter(alllist) of type FilterResult!(__lambda1, string[]) to string[]
    

    问题在哪里,如何解决?谢谢。

    0 回复  |  直到 7 年前
        1
  •  4
  •   BioTronic    7 年前

    正如您所发现的,返回值 filter 不是数组,而是自定义范围。 滤波器 的返回值实际上是一个延迟范围,因此如果只使用前几个项,则只计算这些项。要将延迟范围转换为数组,需要使用 std.array.array :

    import std.array : array;
    alllist = alllist.filter!(a => a.indexOf(str) >= 0).array;
    

    import std.stdio;
    import std.string;
    import std.file : readText;
    import std.algorithm;
    import std.array;
    
    void main() {
        string[] srchitems = ["second", "pen"];
        auto alltext = readText("testing.txt");
        auto alllist = alltext.split("\n");
        auto results = alllist.filter!(a => srchitems.any!(b => a.indexOf(b) >= 0));
        writeln(results);
    }
    

    在上面的代码中,我们使用 滤波器