filterBidirectional

auto filterBidirectional(Range)(Range r) if (isBidirectionalRange!(Unqual!Range));

Similar to filter, except it defines a bidirectional range. There is a speed disadvantage - the constructor spends time finding the last element in the range that satisfies the filtering condition (in addition to finding the first one). The advantage is that the filtered range can be spanned from both directions. Also, std.range.retro can be applied against the filtered range.

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 filterBidirectional(alias pred)
filterBidirectional
(
Range
)
(
Range r
)
if (
isBidirectionalRange!(Unqual!Range)
)

Parameters

pred

Function to apply to each element of range

r

Bidirectional range of elements

Return Value

a new range containing only the elements in r for which pred returns true.

Examples

1 import std.algorithm.comparison : equal;
2 import std.range;
3 
4 int[] arr = [ 1, 2, 3, 4, 5 ];
5 auto small = filterBidirectional!("a < 3")(arr);
6 static assert(isBidirectionalRange!(typeof(small)));
7 assert(small.back == 2);
8 assert(equal(small, [ 1, 2 ]));
9 assert(equal(retro(small), [ 2, 1 ]));
10 // In combination with chain() to span multiple ranges
11 int[] a = [ 3, -2, 400 ];
12 int[] b = [ 100, -101, 102 ];
13 auto r = filterBidirectional!("a > 0")(chain(a, b));
14 assert(r.back == 102);

Meta