if then (else) expressions

“if” expressions are now supported in DWScript SVN, those were introduced to Pascal by Oxygene a couple years back, and are Pascal’s verbose version of the C ternary operator (?:).

For instance

var s := if (a<>0) then Sin(1/a) else 1;

being equivalent to

var s : Float;
if (a<>0) then
   s := Sin(1/a)
else s := 1;

This can allow to eliminate the need for some intermediate variables and repetitions.

However the DWScript version is a bit stricter than the Oxygene version in that it won’t automatically box incompatible values to “Object”, it it will also not introduce a nullable type on its own for the result. If the “else” alternative is not present, the value of the expressions will be that that of the type’s default, ie. both following lines would be equivalent:

var msg1 := "There are " + IntToStr(n) + " user" + (if (n>1) then "s" else "");
var msg2 := "There are " + IntToStr(n) + " user" + if (n>1) then "s";

(as a reminder DWScript accepts both ” and ‘ to define strings)

4 thoughts on “if then (else) expressions

  1. I must say that I don’t really like this syntax. I much prefer the Python syntax for the conditional operator. And by the way, the C, C++, C# etc. operators are officially known as the conditional operator.

    Anyway, in Python you’d write

    s = math.sin(1/a) if a != 0 else 1

    I just find the idea of assigning if to a variable rather odd to look at.

    I guess like all these things, what you are used to is critical and in time the Oxygene syntax would read fine.

  2. I love it. I am so pissed with IfThen() and mostly due to the fact that IfThen() overloads are available in different units and you have to recall was it StrUtils, Math, or something else you need to include.

  3. Amazing to see new fetures introduced to DWScript almost every week. I my self doesn’t use it but I like to read about it.

    Embarcadero could learn a thing or two from this project (o;

Comments are closed.