开发者

Erlang compound boolean expression

开发者 https://www.devze.com 2022-12-13 17:42 出处:网络
I read the documentation about using and, or operators, but why is the following not evaluating? X = 15,

I read the documentation about using and, or operators, but why is the following not evaluating?

X = 15,
Y = 20,
X==15 and Y==20.

I am expecting for a "true" in the terminal, but I get a "syntax开发者_运维知识库 error before ==".


Try:

X = 15.
Y = 20.
(X==15) and (Y==20).


You probably don't want to use and. There are two problems with and, firstly as you've noticed its precedence is strange, secondly it doesn't short circuit its second argument.

1> false and exit(oops).
** exception exit: oops
2> false andalso exit(oops).
false

andalso was introduced later to the language and behaves in the manner which is probably more familiar. In general, use andalso unless you have a good reason to prefer and.

Btw, orelse is the equivalent of or.


Without braces you can also do

X = 15.
Y = 20.
X == 15 andalso Y == 20.


herre's the operator precedence / binding rules table, for future reference

http://www.erlang.org/doc/reference_manual/expressions.html#id2274242

============

here's some erlang "gotcha" lists i found helpful

Learning Erlang? speedbump thread, common, small problems

http://www.erlang.org/faq/problems.html

http://baphled.wordpress.com/2009/01/05/lighting-up-the-tunnerl-pt-3-afterl-the-basics/

http://baphled.wordpress.com/2009/03/13/lighting-up-the-tunnerl-pt-9-the-gotchaz/

0

精彩评论

暂无评论...
验证码 换一张
取 消