choose

Choose one of two ranges at runtime depending on a Boolean condition.

The ranges may be different, but they must have compatible element types (i.e. CommonType must exist for the two element types). The result is a range that offers the weakest capabilities of the two (e.g. ForwardRange if R1 is a random-access range and R2 is a forward range).

choose
(
R1
R2
)
(,
return scope R1 r1
,
return scope R2 r2
)

Parameters

condition bool

which range to choose: r1 if true, r2 otherwise

r1 R1

the "true" range

r2 R2

the "false" range

Return Value

Type: auto

A range type dependent on R1 and R2.

Examples

1 import std.algorithm.comparison : equal;
2 import std.algorithm.iteration : filter, map;
3 
4 auto data1 = only(1, 2, 3, 4).filter!(a => a != 3);
5 auto data2 = only(5, 6, 7, 8).map!(a => a + 1);
6 
7 // choose() is primarily useful when you need to select one of two ranges
8 // with different types at runtime.
9 static assert(!is(typeof(data1) == typeof(data2)));
10 
11 auto chooseRange(bool pickFirst)
12 {
13     // The returned range is a common wrapper type that can be used for
14     // returning or storing either range without running into a type error.
15     return choose(pickFirst, data1, data2);
16 
17     // Simply returning the chosen range without using choose() does not
18     // work, because map() and filter() return different types.
19     //return pickFirst ? data1 : data2; // does not compile
20 }
21 
22 auto result = chooseRange(true);
23 assert(result.equal(only(1, 2, 4)));
24 
25 result = chooseRange(false);
26 assert(result.equal(only(6, 7, 8, 9)));

Meta

Suggestion Box / Bug Report