【发布时间】:2020-04-07 02:28:59
【问题描述】:
我阅读了有关使用 and、or 运算符的文档,但为什么以下内容没有评估?
X = 15,
Y = 20,
X==15 and Y==20.
我期待终端中出现“true”,但在 ==" 之前出现“语法错误”。
【问题讨论】:
我阅读了有关使用 and、or 运算符的文档,但为什么以下内容没有评估?
X = 15,
Y = 20,
X==15 and Y==20.
我期待终端中出现“true”,但在 ==" 之前出现“语法错误”。
【问题讨论】:
试试:
X = 15.
Y = 20.
(X==15) and (Y==20).
【讨论】:
您可能不想使用 and。 and 有两个问题,首先你注意到它的优先级很奇怪,其次它不会短路它的第二个参数。
1> false and exit(oops).
** exception exit: oops
2> false andalso exit(oops).
false
andalso 是后来被引入该语言的,其行为方式可能更熟悉。一般来说,使用 andalso,除非你有充分的理由更喜欢 and。
顺便说一句,orelse 相当于 or。
【讨论】:
不用大括号也可以
X = 15.
Y = 20.
X == 15 andalso Y == 20.
【讨论】:
这里是运算符优先级/绑定规则表,供以后参考
http://www.erlang.org/doc/reference_manual/expressions.html#id2274242
============
这里有一些我发现有用的 erlang “陷阱”列表
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/
【讨论】: