Does any programming language implement swapping of arguments of logical operation (such as AND, OR) for faster evaluation?
Example (I think such method could be implemented in a lazy evaluation language like Haskell)
A
and B
. B
was evaluated to "True" and A
was not evaluatedIF A OR B
IF B OR A
A
Under lazy evaluation, AND and OR are not commutative.
foo :: Int -> Bool
foo n = False && foo (n+1) -- evaluates to False
bar :: Int -> Bool
bar n = bar (n+1) && False -- diverges
Under eager evaluation (strict semantics), and absence of side effects, they are commutative. I am not aware of any usual optimization being done by some compiler here, though. (Constants folding aside.)
If side effects are present, AND/OR are not commutative, of course. For instance, an Ocaml compiler can not swap the arguments unless it can prove that at least one of them is side effect-free.