逻辑或与逻辑与:哪个应该更具约束力?
我正在编写一个小型解析器,它将有一个 OR 运算符和一个 AND 运算符。当您看到一系列 OR 和 AND 时,您认为哪一个更具约束力?给定表达式 a &乙| c
,你认为它的意思是(a&b)|c
还是a&(b|c)
?您能给出任何理由选择其中一种而不是另一种吗?
I'm writing a small parser, which will have an OR operator and an AND operator. When you see a series of ORs and ANDs, which do you expect will be more binding? Given the expression a & b | c
, do you expect it to mean (a&b)|c
or a&(b|c)
? Can you give any reason to prefer one over the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
做别人都做的事; AND 比 OR 结合得更紧密(请参见C 运算符优先级表)。这是每个人都期望的约定,因此请采用最小惊喜原则。
这个选择并不是任意的。它源于这样一个事实:AND 和 OR 分别遵循与乘法和加法类似的关系;参见例如http://en.wikipedia.org/wiki/Boolean_logic#Other_notations。
另请注意,应大力鼓励使用您的语言的用户使用括号,以使代码的读者清楚地了解他们的意图。但这取决于他们!
Do what everyone else does; AND binds tighter than OR (see e.g. C Operator Precedence Table). This is the convention that everyone expects, so adopt the principle of least surprise.
This choice isn't arbitrary. It stems from the fact that AND and OR follow a similar relationship to multiply and add, respectively; see e.g. http://en.wikipedia.org/wiki/Boolean_logic#Other_notations.
Note also that users of your language should be heavily encouraged to use parentheses to make their intentions clear to readers of their code. But that's up to them!
布尔代数中的 AND 和 OR 相当于正则代数中的 * 和 -,因此 AND 比 OR 更难结合是有道理的,就像 * 比 + 更难结合一样:
AND and OR in Boolean algebra are equivalent to * and - in regular algebra, so it makes sense that AND binds harder than OR just like * binds harder than +:
如果您像离散数学一样考虑它,我会说 PEMDAS 会引导您说AND 更具约束力。但情况并非总是如此。
我建议您建议您的用户在有歧义的地方使用括号。
If you consider it like you would discrete maths, I'd say PEMDAS leads you to say that the AND is more binding. That's not always the case though.
I recommend you recommending your users to use parentheses wherever there's ambiguity.
通常&优先于 |在很多场景中。但您可以将表达式限制为完整括号形式。
Usually & has a precedence over | in many scenarios. But you can restrict expressions to be in a full parenthesis form.