The OpenD Programming Language

filter

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

The predicate is passed to std.functional.unaryFun, and can be either a string, or any callable that can be executed via pred(element).

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

Members

Functions

filter
auto filter(Range range)

Parameters

predicate

Function to apply to each element of range

Return Value

An input range that contains the filtered elements. If range is at least a forward range, the return value of filter will also be a forward range.

Examples

import std.algorithm.comparison : equal;
import std.math.operations : isClose;
import std.range;

int[] arr = [ 1, 2, 3, 4, 5 ];

// Filter below 3
auto small = filter!(a => a < 3)(arr);
assert(equal(small, [ 1, 2 ]));

// Filter again, but with Uniform Function Call Syntax (UFCS)
auto sum = arr.filter!(a => a < 3);
assert(equal(sum, [ 1, 2 ]));

// In combination with chain() to span multiple ranges
int[] a = [ 3, -2, 400 ];
int[] b = [ 100, -101, 102 ];
auto r = chain(a, b).filter!(a => a > 0);
assert(equal(r, [ 3, 400, 100, 102 ]));

// Mixing convertible types is fair game, too
double[] c = [ 2.5, 3.0 ];
auto r1 = chain(c, a, b).filter!(a => cast(int) a != a);
assert(isClose(r1, [ 2.5 ]));

See Also

Meta