On Monday, 6 November 2017 at 00:20:09 UTC, Neia Neutuladh wrote:
On Saturday, 28 October 2017 at 11:38:52 UTC, Andrei Alexandrescu wrote:
Walter and I decided to kick-off project Elvis for adding the homonym operator to D.

It's easy to write in function form:

  auto orElse(T)(T a, lazy T b)
  {
    return a ? a : b;
  }

  writeln(args[1].length.orElse(fibonacci(50)));

This version can also be specialized for things like Nullable, where you can't necessarily cast it safely to a boolean but have a check for validity.

Is it that valuable to have an operator for it instead?


As an aside, I believe feepingcreature had a custom infix operator for this sort of thing defined, so you could write:

  (a /or/ b /or/ c).doStuff();

The implementation (along with /and/) is left as an exercise to the reader.

Sure you might be able to write it easily, but pretty much everyone writes a function like that in their projects and you don\t really know the implementation always and you have to remember the exact name or else you end up writing the function yourself in your project to make sure the implementation is exactly like that, which in fact turns out to be re-inventing the wheel.

By having an official syntax for it, you don't end up with code duplication like that and the implementation details of the behavior is clear.

Because in some implementation "orElse()" might only check if the value is null and not necessary if the value is true.

Ex. one might implement it like:

   auto orElse(T)(T a, lazy T b)
   {
     return a !is null ? a : b;
   }

Such implementation detail is not clear from the call-side.

However with an official implementation you know exactly how it will behave and nothing is obscure like this.

Reply via email to