View source code
Display the source code in std/algorithm/iteration.d from which this page was generated on
github.
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.
Page wiki
View or edit the community-maintained wiki page associated with this page.
Template std.algorithm.iteration.filter
auto
filter
(Range)(Range rs) if (isInputRange!(Unqual!Range));
Implements the higher order filter function.
Arguments
template filter(alias predicate);
Functions
Function name | Description |
---|---|
filter |
Parameters
Name | Description |
---|---|
predicate | Function to apply to each element of range |
range | Input range of elements |
Returns
returns a new range containing only elements filter
!(predicate)(range)x
in range
for
which predicate(x)
returns true
.
See Also
Example
import std.algorithm.comparison : equal; import std.math : approxEqual; import std.range; int[] arr = [ 1, 2, 3, 4, 5 ]; // Sum all elements auto small = filter!(a => a < 3)(arr); assert(equal(small, [ 1, 2 ])); // Sum 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 ]));