View source code
Display the source code in std/range/package.d from which this
page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a
Bugzilla issue.
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.
Function std.range.choose
Choose one of two ranges at runtime depending on a Boolean condition.
auto choose(R1, R2)
(
bool condition,
scope return R1 r1,
scope return R2 r2
)
if (isInputRange!(Unqual!R1) && isInputRange!(Unqual!R2) && !is(CommonType!(ElementType!(Unqual!R1), ElementType!(Unqual!R2)) == void));
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).
Parameters
Name | Description |
---|---|
condition | which range to choose: r1 if true , r2 otherwise |
r1 | the "true" range |
r2 | the "false" range |
Returns
A range type dependent on R1
and R2
.
Example
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)));
Authors
Andrei Alexandrescu, David Simcha, Jonathan M Davis, and Jack Stouffer. Credit for some of the ideas in building this module goes to Leonardo Maffi.
License
Copyright © 1999-2022 by the D Language Foundation | Page generated by ddox.