問題描述
如果你試圖找出一個 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.
這篇關于檢查 int 是否在兩個數字之間的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!