View source code
Display the source code in std/algorithm/iteration.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Template std.algorithm.iteration.filter

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

template filter(alias predicate) ;

Contained Functions

NameDescription
filter

Parameters

NameDescription
predicate Function to apply to each element of range

Returns

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

See Also

Filter (higher-order function)

Example

import std.algorithm.comparison : equal;
import std.math : approxEqual;
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(approxEqual(r1, [ 2.5 ]));

Authors

Andrei Alexandrescu

License

Boost License 1.0.