On Wednesday, 12 January 2022 at 06:58:47 UTC, vit wrote:
On Wednesday, 12 January 2022 at 06:43:40 UTC, forkit wrote:
On Wednesday, 12 January 2022 at 06:16:49 UTC, vit wrote:
Yes std.algorithm : filter.
```d
import std.stdio : writeln;
import std.algorithm : filter;
void main()@safe{
auto a = ["one", "one", "two", "one", "two", "one",
"one", "two"];
writeln(a);
writeln(a.filter!(x => x == "one"));
}
```
Interesting. I looked it up.. it says "returns a new range..."
Does that mean what I think it means (i.e. a new allocation
takes place) ?
No, it is only view to old slice:
```d
void main()@safe{
auto a = ["one", "one", "two", "one", "two", "one", "one",
"two"];
auto b = (()@nogc => a.filter!(x => x == "one"))();
writeln(a);
writeln(b);
}
```
filter is implemented like this (but more generic):
```d
import std.stdio : writeln;
auto filter(alias fn, T)(T[] slice){
//InputRange:
static struct Filter{
T[] slice;
bool empty()const{return slice.length == 0;}
T front(){return slice[0];}
void popFront(){
do{
slice = slice[1 .. $];
}while(slice.length && !fn(slice[0]));
}
}
return Filter(slice);
}
void main()@safe{
auto a = ["one", "one", "two", "one", "two", "one", "one",
"two"];
writeln(a);
writeln(a.filter!(x => x == "one"));
}
```