possible improvement to if statements?

Sebastiaan Koppe mail at skoppe.eu
Mon Apr 27 15:45:41 UTC 2020


On Sunday, 26 April 2020 at 21:26:31 UTC, Steven Schveighoffer 
wrote:
> Is this located anywhere on code.dlang.org or in phobos?

No, hence the awful name.

> But there is one issue -- what if P defines opCast(bool)?

I think you can introspect that in the opCast function, and if 
so, forward the call if p !is null.

That still leaves you with the downside of wrapping the (x in y) 
expression.

You could also argue that the (x in y) expression needs to return 
an optional. If ever there was a need for optional this would be 
it. If fact the Wrap thing I wrote is dangerously close to the 
nullable, including it's flaws, namely that it automatically 
dereferences p.

A more function approach might be better. Gets rid of the control 
flow as well.

y.get(x)
   .then(x => writeln(x));   // prints only when x is in y

y.get(x)
   .withDefault(55)
   .then(x => writeln(x));   // prints x or 55

y.get(x)
   .then(x => writeln(x))
   .orElse({ throw new Exception("not found")});   // prints x or 
throws


More information about the Digitalmars-d mailing list