Create array from range

jfondren julian.fondren at
Sun Oct 10 00:14:51 UTC 2021

On Saturday, 9 October 2021 at 23:58:14 UTC, Greg Strong wrote:
> This should be a simple question, but I'm having difficult 
> finding an answer.  How do I filter some elements of an array 
> into a new array?  The filter! function returns a range, but I 
> can't seems to assign it to a new array.  I get:
> Cannot implicitly convert expression of type 
> FilterResult!(__lambda10 ...
> Nothing I try to construct a new array seems to work.

std.array.array does this:

and some other functions in that module are similar.

A value of output ranges like FilterResult is that you can decide 
how or whether to allocate an array of the results: you could 
allocate a new array with `.array` or you could consume the 
results as they come, or you could out pick a particular result, 
or you could populate a static array...

int example(R)(R range) @nogc {
     import std.range : take, enumerate;

     int[5] ints;

     foreach (size_t i, n; range.enumerate.take(ints.length))
         ints[i] = n;

     // just to do something with the array
     int sum;
     foreach (n; ints)
         sum += n;
     return sum;

unittest {
     import std.range : iota;
     import std.algorithm : filter;

     assert(20 == iota(100).filter!"a%2==0".example);

More information about the Digitalmars-d-learn mailing list