Count your blessings!

bearophile bearophileHUGS at lycos.com
Thu Jun 11 05:14:25 PDT 2009


Robert Fraser:
> As well as the incompatibility with intuition. If anything, I'd think 
> the Elvis operator is more of an "or" since "x ?: y" means "x !is null ? 
> x : y". Doesn't && evaluate both arguments unless the first is false (or 
> in this case, null)?

Yes, it's a relative of "or". In Python the Elvis operator is the "or" itself:

>>> a, b, c = 10, 0, 5
>>> a or b
10
>>> b or a
10
>>> a and b
0
>>> b and a
0
>>> a and c
5
>>> c and a
10

In my dlibs there's a lazyOr() that takes any number of arguments and returns the first one that's true (where true is defined by a standard function boolean() that returns false for 0, null, objects/structs that have a length and where such length is zero).

A reduced (and untested) version that works with two arguments only, that is (I think) the Elvis operator:

Tx lazyOr(Tx, Ty)(Tx x, lazy Ty y) {
    static assert(CastableTypes!(Tuple!(Tx, Ty)), "lazyOr: all items must be castable to the same type.");
    if (boolean(x))
        return x;
    return y();
}

A difference is that the Elvis operator is more efficient because it doesn't need to create a lazy delegate as in the D code (I don't know if LDC is able to optmize away such y delegate).

Bye,
bearophile



More information about the Digitalmars-d mailing list