Project Elvis

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Oct 29 17:19:44 UTC 2017


On Sunday, October 29, 2017 16:44:39 Ola Fosheim Grøstad via Digitalmars-d 
wrote:
> On Sunday, 29 October 2017 at 16:29:57 UTC, Jonathan M Davis
>
> wrote:
> > valid using ?:, I would think that you'd want to be doing the
> > same check with stuff like if statements anyway. So, it sounds
> > to me like overloading opCast!bool would work just fine.
>
> If you try to do:
>
> some_float ?: 0.0
>
> then it will do nothing as cast(bool)std.math.NaN(0) => true

NaN is supposed to always be false.

> But that is just one of many possible examples. The elvis
> operator as proposed does not match on nullity / invalid state.

Well, the closest that the language has to that is cast(bool). There is
nothing else generic for anything along those lines. If you want something
else, then just use the ternary operator with whatever condition you want to
be testing. It works just fine and isn't much longer.

Personally, I don't think that the Elvis operator is worth much - at least
not in D. Idiomatic D code doesn't use classes much. Dynamic arrays largely
conflate null with empty. Very little does anything with null - especially
if you're writing range-based code - and I've rarely seen code where
x ? x : y was used. The closest that I've typically seen or done to
x ? x : y is

if(auto var = foo())
{
}

and that's not useful for much beyond dealing with functions that return
error codes or getting values from associative arrays. And it's not like
using the ternary operator is very verbose. But the whole idea of "check if
this is valid, if it is use it, and if it isn't, use a default" simply isn't
an idiom that I use much, and I don't think that it's very common in Phobos.
I also tend to prefer being explicit about conditions, so I don't typically
rely on things like cast(bool) on types, and that's exactly the sort of
thing that the Elvis operator would rely on whether it used cast(bool) or it
was overloaded as its own operator like you seem to want.

So, I really don't think that there's any point in adding the Elvis
operator, but there are some folks here who seem to think that it's a great
loss that we don't have it, because they're used to writing stuff like that
in languages like C#, which do way more with classes and null than D code
typically does.

- Jonathan M Davis




More information about the Digitalmars-d mailing list