没有多余括号的算术表达式的明确语法
我正在寻找一种没有多余括号的算术表达式的明确语法。例如,括号在 id+(id*id)
中是多余的,但在 (id+id)*id
中则不是。
I am looking for an unambiguous grammar for arithmetic expressions with no redundant parentheses. For example, parentheses are redundant in id+(id*id)
, but not in (id+id)*id
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以轻松做到这一点。唯一需要括号的情况是减法右侧的和、乘法右侧的和或除法右侧的和或乘法。
您希望按如下方式解析表达式:
表达式可以是单个值,也可以是总和或乘积。
和是一个或多个乘法项或单个值的和或差,我们从左到右相加,因此我们从右到左解析;减法的右侧可以是括号内的和(但不能是括号内的乘法)。
产品的右侧有一个值或一个括号内的总和;括号乘法也可以位于除法的右侧,但值不能。值永远不能放在括号中。
我很确定这一点
我希望这有帮助!
一段时间后编辑:我犯了一些错误,即我没有正确处理加法。我意识到减法是一个问题。我简化了系统并解决了问题。
括号只能出现在除法右侧的非平凡乘积周围,或者除法、乘法或减法右侧的非平凡和周围,或者位于产品的左侧。
You can easily do this. The only time when parentheses become necessary is a sum to the right of a subtraction, a sum to the right of a multiplication, or a sum or multiplication to the right of a division.
You want to parse the expression as such:
An expression is either a single value, or a sum or product.
A sum is the sum or difference of one or more multiplicative terms or individual values, which we add left to right, so we parse right to left; the right side of a subtraction can be a parenthetical sum (but not a parenthetical multiplication).
A product has either a value or a parenthetical sum to the right of it; parenthetical multiplications can be to the right of a division, too, but values cannot. Values can never be in parentheses.
I'm pretty sure this
I hope this helps!
Editing some time later: I had made some mistakes, namely that I didn't handle addition correctly. I realized that subtraction is a problem. I've simplified the system and fixed the problems.
The only time parentheses can show up is around a nontrivial product that is to the right of a division, or around a nontrivial sum that is to the right of a division, a multiplication, or a subtraction, or around a sum that is at the left of a product.
这完全取决于“对于没有多余括号的算术表达式”的含义。这将接受没有多余括号的表达式,但也接受任意嵌套的括号:
我假设 NUMBER 设法识别有符号数字,因此其中没有一元加号或减号。如果需要,您可以弄清楚如何处理它们。如果需要,您还可以添加变量等。
如果您的意思是拒绝具有不必要括号的表达式的语法,那么我认为您正在寻找不是上下文无关语法的东西。
It depends on exactly what you mean by 'for arithmetic expressions with no redundant parentheses'. This will accept expressions with no redundant parentheses, but will also accept arbitrarily nested parentheses:
I'm assuming that NUMBER manages to recognize signed numbers, so there is no unary plus or minus in there. You can work out how to handle them if you need them. You can also add variables etc if you need them.
If you mean a grammar that rejects expressions that have unnecessary parentheses, then I think you are on a search for the something that is not a context-free grammar.