View source code
Display the source code in std/algorithm/comparison.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.algorithm.comparison.either

Get the first argument a that passes an if (unaryFun!pred(a)) test. If no argument passes the test, return the last argument.

CommonType!(T,Ts) either(alias pred, T, Ts...) (
  T first,
  lazy Ts alternatives
)
if (alternatives.length >= 1 && !is(CommonType!(T, Ts) == void) && allSatisfy!(ifTestable, T, Ts));

Similar to behaviour of the or operator in dynamic languages such as Lisp's (or ...) and Python's a or b or ... except that the last argument is returned upon no match.

Simplifies logic, for instance, in parsing rules where a set of alternative matchers are tried. The first one that matches returns it match result, typically as an abstract syntax tree (AST).

Bugs

Lazy parameters are currently, too restrictively, inferred by DMD to always throw even though they don't need to be. This makes it impossible to currently mark either as nothrow. See issue at Bugzilla 12647.

Returns

The first argument that passes the test pred.

Example

const a = 1;
const b = 2;
auto ab = either(a, b);
static assert(is(typeof(ab) == const(int)));
writeln(ab); // a

auto c = 2;
const d = 3;
auto cd = either!(a => a == 3)(c, d); // use predicate
static assert(is(typeof(cd) == int));
writeln(cd); // d

auto e = 0;
const f = 2;
auto ef = either(e, f);
static assert(is(typeof(ef) == int));
writeln(ef); // f

Example

immutable p = 1;
immutable q = 2;
auto pq = either(p, q);
static assert(is(typeof(pq) == immutable(int)));
writeln(pq); // p

writeln(either(3, 4)); // 3
writeln(either(0, 4)); // 4
writeln(either(0, 0)); // 0
writeln(either("", "a")); // ""

Example

string r = null;
writeln(either(r, "a")); // "a"
writeln(either("a", "")); // "a"

immutable s = [1, 2];
writeln(either(s, s)); // s

writeln(either([0, 1], [1, 2])); // [0, 1]
writeln(either([0, 1], [1])); // [0, 1]
writeln(either("a", "b")); // "a"

static assert(!__traits(compiles, either(1, "a")));
static assert(!__traits(compiles, either(1.0, "a")));
static assert(!__traits(compiles, either('a', "a")));

Authors

Andrei Alexandrescu

License

Boost License 1.0.