检查 int 是否在两个数字之间

2022-01-14 00:00:00 integer conditional-operator java

如果你试图找出一个 int 是否介于两个数字之间,为什么不能这样做:

Why can't do you this if you try to find out whether an int is between to numbers:

if(10 < x < 20)

你必须这样做

if(10<x && x<20)

这似乎有点开销.

推荐答案

一个问题是三元关系构造会引入严重的解析器问题:

One problem is that a ternary relational construct would introduce serious parser problems:

<expr> ::= <expr> <rel-op> <expr> |
           ... |
           <expr> <rel-op> <expr> <rel-op> <expr>

当您尝试使用典型的 PGS 来表达这些产生式的语法时,您会发现在第一个 <rel-op> 处存在移位归约冲突.解析器需要先查看任意数量的符号,以查看是否存在第二个 <rel-op>,然后才能确定使用的是二进制还是三元形式.在这种情况下,您不能简单地忽略冲突,因为这会导致解析不正确.

When you try to express a grammar with those productions using a typical PGS, you'll find that there is a shift-reduce conflict at the point of the first <rel-op>. The parse needs to lookahead an arbitrary number of symbols to see if there is a second <rel-op> before it can decide whether the binary or ternary form has been used. In this case, you could not simply ignore the conflict because that would result in incorrect parses.

我并不是说这个语法是致命的模棱两可.但我认为你需要一个回溯解析器来正确处理它.对于以快速编译为主要卖点的编程语言来说,这是一个严重的问题.

I'm not saying that this grammar is fatally ambiguous. But I think you'd need a backtracking parser to deal with it correctly. And that is a serious problem for a programming language where fast compilation is a major selling point.

相关文章