In standard logic And
is a commutative operator. Still, in Mathematica, And
doesn't have the Orderless
attribute:
Attributes[And]
(* {Flat,HoldAll,OneIdentity,Protected} *)
This may have not been the case in the past. On page 190 of David Wagner's book "Power Programming with Mathematica" one finds a table with functions having different attributes. In that table And
is listed as one of the functions that have the Orderless
attribute. At the time of publication Mathematica version 3.0 had just released.
There are good reasons for And
not to have Orderless
among its attributes. One of them is efficiency. Since the argument order remains fixed, the programmer can sort the arguments so that the expected execution time will be minimized.
Another reason for eschewing Orderless
is that, in Operator[x,y]
, the evaluation of x
can have such side effects on y
, and perhaps this may cause Operator[x,y]
and Operator[y,x]
have different values (I am not sure about this). However, this second argument for not including Orderless
in the list of attributes of And
also applies to functions like Max
, Times
, and Plus
, and still all of these functions have the Orderless
attribute.
One can see the consequences of these choices:
(x + y) == (y + x)
(* True *)
(x && y) == (y && x)
(* (x && y) == (y && x) *)
So was Orderless
avoided in And
just for efficiency reasons or is there any other specific feature of And
that requires not including Orderless
among its attributes?
And
is notOrderless
so it can be short circuiting. This is not only about efficiency. You can also do stuff likeFooQ[x] && FunnyFooQ[x]
whereFunnyFooQ
won't even run without errors for something that is not a "Foo". Short circuiting makes it possible to write more concise and therefore clearer code without too manyIf
s. $\endgroup$