Search code examples
filterd

Why filter for a list of strings is causing error here


I am trying to filter a list of strings to get only those which have a length more than one using following code:

import std.stdio;
import std.string;
import std.algorithm;

void main(){
    auto slist = ["a","aa","b","bb","c","cc","dd",]; 
    slist = slist.filter!(a => a.length>1);     // does not work; 
    writeln(slist); 
}

However, it is creating error:

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

Where is the problem and how can it be solved? Thanks for your help.


Solution

  • filter returns a lazy range, which cannot be implicitly converted back to a string[]. You can either assign it to a new variable, or evaluate it to an array using std.array.array:

    slist = slist.filter!(a => a.length>1).array;
    writeln(slist);
    

    — or —

    auto slist2 = slist.filter!(a => a.length>1);
    writeln(slist2);