[M3devel] in defense of ternary operator (Ada has it now)
Rodney M. Bates
rodney_bates at lcwb.coop
Thu Oct 18 17:28:57 CEST 2012
On 10/17/2012 07:11 PM, Hendrik Boom wrote:
> On Wed, Oct 17, 2012 at 01:08:01AM +0000, Jay K wrote:
>> In defense of ternary operator:Ada 2012 has equivalent of C/C++'s ternary operator:
>> e.g.
>> sign := if a >= 0 then 1 else -1
>> They'd rather people NOT do like:
>> sign := ORD(a >= 0) * 1 + ORD(a < 0) * -1
>> http://www.adacore.com/uploads/technical-papers/Ada2012_Rationale_Chp2_expressions.pdf
>> "It should be remembered that the difficulties in C stem from a combination of things - That assignment is permitted as an expression, - That integer values are used as Booleans, - That null statements are invisible.
>> None of these applies to Ada so all is well" Modula-3 is also safe from the first two, I don't know about the last. - Jay
>
> This syntax originated a long time ago, with Algol 60. It wasn't a
> problem there, even though empty statements were invisible there, too.
> These, howerver, are expressions, and there are no empty expressions in
> either Algol 60 or Modula 3.
>
> The only problemm was the dangling "else" as in
> if ... then if ... then ... else ...
> But that's only a problem with statements, singe expressions always have
> to have their else's.
>
> For consistency of notation, IF expressions in Modula 3 should probably
> have explicit ENDs, as in Algol 68.
Yes. There is a somewhat different syntax problem here.
Would:
IF B THEN T ELSE IF C THEN U ELSE IF D THEN V ELSE F
Mean:
IF B THEN T ELSE (IF C THEN U ELSE IF D THEN V ELSE F) (* IF is right-associative. *)
Or:
IF B THEN T ELSE IF C THEN U ELSE (IF D THEN V ELSE F) (* IF is left-associative. *)
Would:
IF B THEN T ELSE E OR F
Mean:
IF B THEN T ELSE (E OR F) (* OR has higher precedence than IF. *)
Or:
(IF B THEN T ELSE E) OR F (* OR has lower precedence than IF. *)
Precedence and associativity rules for the IF-expression would resolve
these, and all the existing expression operators have these properties.
But somehow, the IF-expression intuitively seems to me to be a lot harder
to follow than for more traditional infix operators.
And for associativity there is an unusual asymmetry about it. At first,
I wanted to write
(IF B THEN T ELSE IF C THEN U ELSE) IF D THEN V ELSE F (* IF is left-associative. *)
But that's really wierd, and would make
IF B THEN T ELSE IF C THEN U ELSE (* Nothing here *)
an expression, which breaks everything.
Giving it a closing END seems a lot easier to fix the syntax and
easier to read.
>
> -- hendrik
>
>
More information about the M3devel
mailing list