www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 21783] New: Add `if` as an operator


          Issue ID: 21783
           Summary: Add `if` as an operator
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: qs.il.paperinik gmail.com

Make `if` a binary infix operator on the same precedence level as the trinary
operator. Its semantics would be: (lhs if rhs) is lowered to (!(rhs) || lhs).

The big win is when stating invariants or preconditions and especially
post-conditions. IMO, those should be easy to understand for the common
programmer. The alternatives are just bad as they aren't grasped as an
implication (usually, one goes the route over the rewrite above). The best I
could come up with is

    lhs ? rhs : true

which at least uses something that is recognized as an implication.

As an example, this could be the contracted version of a divMod implementation:

    void divMod(int a, int b, int q, int r)
        in (b > 0)
        out (; q <= 0 if a < 0)
        out (; q >= 0 if a > 0)
        out (; r <= 0 if a < 0)
        out (; r >= 0 if a > 0)
    { ... }

I find it really hard to formulate these in a comprehensive manner without an
`if` operator.

Mar 29 2021