I am curious why the comma ‹,› is a shortcut for and
and not andalso
in guard tests.
Since I'd call myself a “C native” I fail to see any shortcomings of short-circuit boolean evaluation.
I compiled some test code using the to_core
flag to see what code is actually generated. Using the comma, I see the left hand value and right and value get evaluated and both and'ed. With andalso
you have a case block within the case block and no call to erlang:and/2
.
I did no benchmark tests but I daresay the andalso
variant is the faster one.
Adam Lindbergs link is right. Using the comma does generate better beam code than using andalso. I compiled the following code using the +to_asm flag:
which generates
I only looked into what is generated with the +to_core flag, but obviously there is a optimization step between to_core and to_asm.
The boolean operators "and" and "or" always evaluate arguements on both the sides of the operator. Whereas if you want the functionality of C operators && and || (where 2nd arguement is evaluated only if needed..for eg if we want to evalue "true orelse false" as soon as true is found to be the first arguement, the second arguement will not be evaluated which is not the case had "or" been used ) go for "andalso" and "orelse".
It's an historical reason.
and
was implemented beforeandalso
, which was introduced in Erlang 5.1 (the only reference I can find right now is EEP-17). Guards have not been changed because of backwards compatibility.To delve into the past:
Originally in guards there were only
,
separated tests which were evaluated from left-to-right until either there were no more and the guard succeeded or a test failed and the guard as a whole failed. Later;
was added to allow alternate guards in the same clause. If guards evaluate both sides of a,
before testing then someone has gotten it wrong along the way. @Kay's example seems to imply that they do go from left-to-right as they should.Boolean operators were only allowed much later in guards.
and
, together withor
,xor
andnot
, is a boolean operator and was not intended for control. They are all strict and evaluate their arguments first, like the arithmetic operators+
,-
,*
and '/'. There exist strict boolean operators in C as well.The short-circuiting control operators
andalso
andorelse
were added later to simplify some code. As you have said the compiler does expand them to nestedcase
expressions so there is no performance gain in using them, just convenience and clarity of code. This would explain the resultant code you saw.N.B. in guards there are tests and not expressions. There is a subtle difference which means that while using
and
andandalso
is equivalent to,
usingorelse
is not equivalent to;
. This is left to another question. Hint: it's all about failure.So both
and
andandalso
have their place.