The OpenD Programming Language

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

import std.algorithm.comparison : equal;
import std.algorithm.iteration : filter, map;

auto data1 = only(1, 2, 3, 4).filter!(a => a != 3);
auto data2 = only(5, 6, 7, 8).map!(a => a + 1);

// choose() is primarily useful when you need to select one of two ranges
// with different types at runtime.
static assert(!is(typeof(data1) == typeof(data2)));

auto chooseRange(bool pickFirst)
{
    // The returned range is a common wrapper type that can be used for
    // returning or storing either range without running into a type error.
    return choose(pickFirst, data1, data2);

    // Simply returning the chosen range without using choose() does not
    // work, because map() and filter() return different types.
    //return pickFirst ? data1 : data2; // does not compile
}

auto result = chooseRange(true);
assert(result.equal(only(1, 2, 4)));

result = chooseRange(false);
assert(result.equal(only(6, 7, 8, 9)));

Meta