为什么需要前缀、后缀表示法
我知道它们如何相互转换,但从未真正理解它们的应用是什么。通常的中缀操作是非常可读的,但是它在哪里失败并导致前缀和后缀表示法的开始
I know how each of them can be converted to one another but never really understood what their applications are. The usual infix operation is quite readable, but where does it fail which led to inception of prefix and postfix notation
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
中缀表示法对于人类来说很容易阅读,而前/后缀表示法对于机器来说更容易解析。前/后缀表示法的一大优点是永远不会出现任何诸如运算符优先级之类的问题。
例如,考虑中缀表达式
1 # 2 $ 3
。现在,我们不知道这些运算符的含义,因此有两种可能的对应后缀表达式:1 2 # 3 $
和1 2 3 $#
。如果不知道这些运算符的使用规则,中缀表达式基本上毫无价值。或者,用更一般的术语来说:可以从前/后缀表达式恢复原始(解析)树,而无需任何额外的知识,但对于中缀表达式则不然。
Infix notation is easy to read for humans, whereas pre-/postfix notation is easier to parse for a machine. The big advantage in pre-/postfix notation is that there never arise any questions like operator precedence.
For example, consider the infix expression
1 # 2 $ 3
. Now, we don't know what those operators mean, so there are two possible corresponding postfix expressions:1 2 # 3 $
and1 2 3 $ #
. Without knowing the rules governing the use of these operators, the infix expression is essentially worthless.Or, to put it in more general terms: it is possible to restore the original (parse) tree from a pre-/postfix expression without any additional knowledge, but the same isn't true for infix expressions.
后缀表示法,也称为 RPN,很容易从左到右处理。操作数被压入堆栈;运算符从堆栈中弹出其操作数并压入结果。很少或不需要解析。它被 Forth 和一些计算器使用(HP 计算器因使用 RPN 而闻名)。
前缀表示法几乎同样容易处理;它用在 Lisp 中。
Postfix notation, also known as RPN, is very easy to process left-to-right. An operand is pushed onto a stack; an operator pops its operand(s) from the stack and pushes the result. Little or no parsing is necessary. It's used by Forth and by some calculators (HP calculators are noted for using RPN).
Prefix notation is nearly as easy to process; it's used in Lisp.
至少对于前缀表示法的情况:使用前缀运算符的优点是,从语法上讲,它读起来就像运算符是函数调用一样
At least for the case of the prefix notation: The advantage of using a prefix operator is that syntactically, it reads as if the operator is a function call
前缀/后缀与中缀的另一个方面是运算符的数量(它应用于多少个参数)不再必须严格限制为 2。它可以更多,有时也可以更少(当默认值是 0 或 1 时)自然暗示,例如零用于加法/减法,一用于乘法/除法)。
Another aspect of prefix/postfix vs. infix is that the arity of the operator (how many arguments it is applied to) no longer has to be limited to exactly 2. It can be more, or sometimes less (0 or 1 when defaults are implied naturally, like zero for addition/subtraction, one for multiplication/division).