The new ?? and ??? operators

Bill Baxter dnewsgroup at billbaxter.com
Mon Sep 24 14:04:55 PDT 2007


Arlen Albert Keshabyan wrote:
> It would be the sugar syntactic to add '??' operator to D. Consider the example code:
> 
> string error_message = getErrorMessage() ?? "no errors";
> A a = x.getPreparedAObject() ?? y.getPreparedAObject() ?? new A();
> 
> This operator is supposed to do the same thing as C# does: lvalue
evaluates to the first non-null value or to null if all rvalues contains
null. This operator might be extended to '???' to evaluate to a value
that conforms to some conditions. The lvalue gets the first rvalue that
evaluates to true (evaluation goes from left to right). If no conditions
evaluates to true then the lvalue stays unchanged. If no conditions are
given explicitly then those conditions evaluates to true (so, the best
place for them is at the end of a sequence).
> 
> For instance:
> 
> int codeval = getValue1() > 5 ??? getValue2() >= 4 ??? getValue3() != 0 ??? 1; // if no conditions are satisfied then codeval = 1 as a default value at last. There are no sane reasons to place it in the middle of the sequence.
> 
> int code = 7;
> code = 5 < 10 ??? 0 != 0; // this way, code = 7 (no conditions are satisfied)
> 

It would be great to have a way to express

   complicated_expression > 0 ? complicated_expression : default

Without having to duplicate complicated_expression, while still 
remaining an expression overall.

But I find the "a op b ??? default" syntax illogical.  It looks like 'a 
op b' should be evaluated, becoming a boolean.

How about Something like:
    complicated_expression ?> 0 : -1

    evaluates to "complicated_expression if it's greater than zero, 
otherwise -1"

[Of course there are a dozen other bugs and features I'd rather see 
handled before this ;-)]

--bb



More information about the Digitalmars-d mailing list