Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ada short-circuit control forms

Whats the meaning of

x AND THEN y AND z

is it

x AND THEN (y AND z)

(y, z gets never evaluated if x is FALSE) or

(x AND THEN y) AND z

(if x is FALSE, y is skipped, but its possible that z is evaluated) in ada?

like image 801
adaTHENORELSE Avatar asked Jun 05 '11 20:06

adaTHENORELSE


4 Answers

@oenone's comment mentions that GNAT rejects x AND THEN y AND z, but doesn't explain why. It's true, in a sense, that and and and then have the same precedence, but that's not the whole story.

The grammar for an expression is:

expression ::=
  relation {and relation}  | relation {and then relation}
  | relation {or relation} | relation {or else relation}
  | relation {xor relation}

where { FOO } denotes zero or more occurrences of FOO.

This grammar is specifically designed to allow any one of these operators or control forms to be chained in a single expression (X and Y and Z, A and then B and then C), but to forbid mixing them. So the expression in the question, x AND THEN y AND z, is illegal, and the question of what it means doesn't even arise. The point of this rule is precisely to avoid confusion in cases like this.

You just need to write (X and then Y) and Z or X and then (Y and Z), whichever one matches what you want to do.

The same applies to mixing and and or:

    X and Y and Z  -- legal
    X and Y or  Z  -- ILLEGAL
    (X and Y) or Z -- legal
    X and (Y or Z) -- legal
like image 130
Keith Thompson Avatar answered Jan 01 '23 22:01

Keith Thompson


The short-circuit operators have the same precedence as their strict versions.

like image 20
MRAB Avatar answered Jan 01 '23 23:01

MRAB


As Mrab & Ira & trash have said they have equal pecedence, however what has not been pointed out explicitly is that the "and then" & "or else" operators will cause the expression to return (finish evaluation) as soon as a result can be determined.

For example(in pseudocode) :

if Almost_always_true_fn() or else costly_fn() then 
  do_stuff;
end if;

Most of the time only the first function (Almost_always_true_fn) will be evaluated, and only when that returns false will costly_fn be executed.

Compare this with :

if Almost_always_true_fn() or costly_fn() then 
  do_stuff;
end if;

In this case both Almost_always_true_fn() and costly_fn() will be evaluated.

NWS.

like image 28
NWS Avatar answered Jan 01 '23 22:01

NWS


Yes, in (x AND THEN y) AND z, the relation z will always be evaluated.

like image 21
trashgod Avatar answered Jan 01 '23 21:01

trashgod