filter

auto filter(Range)(Range rs) if (isInputRange!(Unqual!Range));

Implements the higher order filter function. The predicate is passed to std.functional.unaryFun, and can either accept a string, or any callable that can be executed via pred(element).

template filter(alias predicate)
filter
(
Range
)
(
Range range
)
if (
isInputRange!(Unqual!Range)
)
if (
is(typeof(unaryFun!predicate))
)

Parameters

predicate

Function to apply to each element of range

range

Input range of elements

Return Value

filter!(predicate)(range) returns a new range containing only elements x in range for which predicate(x) returns true.

Examples

1 import std.algorithm.comparison : equal;
2 import std.math : approxEqual;
3 import std.range;
4 
5 int[] arr = [ 1, 2, 3, 4, 5 ];
6 
7 // Sum all elements
8 auto small = filter!(a => a < 3)(arr);
9 assert(equal(small, [ 1, 2 ]));
10 
11 // Sum again, but with Uniform Function Call Syntax (UFCS)
12 auto sum = arr.filter!(a => a < 3);
13 assert(equal(sum, [ 1, 2 ]));
14 
15 // In combination with chain() to span multiple ranges
16 int[] a = [ 3, -2, 400 ];
17 int[] b = [ 100, -101, 102 ];
18 auto r = chain(a, b).filter!(a => a > 0);
19 assert(equal(r, [ 3, 400, 100, 102 ]));
20 
21 // Mixing convertible types is fair game, too
22 double[] c = [ 2.5, 3.0 ];
23 auto r1 = chain(c, a, b).filter!(a => cast(int) a != a);
24 assert(approxEqual(r1, [ 2.5 ]));

See Also

Meta