What is "FilterResult" type?

cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Sep 8 03:08:02 PDT 2015


On Tuesday, 8 September 2015 at 09:48:35 UTC, Bahman Movaqar 
wrote:
> From what I can gather the output of `std.algorithm.iteration : 
> filter` is a `FilterResult` type.
> I need a bit of help dealing with this type:
>   1. Why this type is there in the first place instead of 
> simply using the type of input range?
>   2. Where is the documentation for this type?  The 
> documentation always uses `auto` for `filter` return values.
>   3. How can I convert this type back into a range?
>
> Thanks.

Filter is a template and returns a FilterResult range which is 
used to lazily compute the result. This behaviour is the same for 
map and the majority of functions in std.algorithm.

It is an input range really (ie: it has front, popFront and 
empty). You can chain it just like any other range with other 
functions and normally don't have to know the exact type (which 
would be complicated since it is a templated thing).

To store it in a variable if you don't know the exact type you 
can use auto to use type deduction. If you need the type (for a 
template for example) you can then use typeof.

Example:

void main() {
     import std.stdio: writeln;
     import std.algorithm: filter, map;

     int[] arr = [1, 2, 3, 4, 5];
     auto result = arr.filter!(x => x%2); // filter out even 
numbers

     result.writeln; // Writes [1, 3, 5];

     // What is the type of result?
     typeid(result).writeln;
     //-> temporary.main.FilterResult!(__lambda2, 
int[]).FilterResult

     // Map takes a range, this works because result is one.
     auto result2 = result.map!(x => 2*x);
     //-> temporary.main.MapResult!(__lambda3, 
FilterResult!(__lambda2,int[])).MapResult

     // Here is the reason you don't want to type them yourself. 
auto FTW!
     typeid(result).writeln; // main.FilterResult!(__lambda2, 
int[]).FilterResult

     // You can put it back in an array too
     import std.array: array;
     int[] resultArr = result2.array;
}

If you want more precise documentation the best is to look to the 
source code (/usr/include/dlang/dmd/std/algorithm/iteration if 
you are on linux).



More information about the Digitalmars-d-learn mailing list