which range to choose: r1 if true, r2 otherwise
the "true" range
the "false" range
A range type dependent on R1 and R2.
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)));
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).