Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need prefix, postfix notation

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

like image 588
Chander Shivdasani Avatar asked Sep 26 '11 23:09

Chander Shivdasani


People also ask

Why do we need postfix expression?

Infix expressions are readable and solvable by humans. We can easily distinguish the order of operators, and also can use the parenthesis to solve that part first during solving mathematical expressions. The computer cannot differentiate the operators and parenthesis easily, that's why postfix conversion is needed.

What is the use of prefix and postfix expression?

Prefix: An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2). Postfix: An expression is called the postfix expression if the operator appears in the expression after the operands.


2 Answers

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 $ and 1 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.

like image 142
Jan Krüger Avatar answered Oct 11 '22 00:10

Jan Krüger


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.

like image 5
Keith Thompson Avatar answered Oct 11 '22 00:10

Keith Thompson