Search code examples
operatorspostfix-mtainfix-notation

infix to postfix with non-commuting operators


I have a question when it comes to - / operators in postfix vs infix.

From the assignment

The input string 5 4 + 3 10 * + is equivalent to the infix expression (5 + 4) + (3 * 10) The answer is 39.

I follow that. Then I get confused by this statement.

We also have to worry about the non-commuting operators – and / . We will evaluate the postfix string 4 5 – as 4 – 5 and, likewise, will evaluate 4 5 / as 4 / 5 .

When I do that however...I get different results with infix vs postfix.

Modifying the first example to include subtraction.

infix

(5 - 4) + (3 * 10) = 31

postfix

5 4 - 3 10 * +

29....right?

SO I'm confused. The results of infix and postfix are supposed to be the same right? Is this a typo in the actual assignment or am I doing something wrong?


Solution

  • When you're evaluating postfix you use a stack: you push operands and when you get to an operator you pop the required operands and push the evaluated result.

    In the case of commutative operators like + it doesn't matter which order the operands are in. So for example:

    5 4 +
    

    can be evaluated as

    PUSH 5
    PUSH 4
    PUSH (POP + POP)
    

    where the first POP will yield 4 and the second POP 5. So you have really evaluated 4+5.

    But in the case of non-commutative operators, this won't work. You have to evaluate 5 / 4, not 4 / 5. So you need either to use temporary variables:

     PUSH 5
     PUSH 4
     let d = POP; // divisor = 4
     let q = POP; // quotient = 5
     PUSH q/d;    // push the dividend
    

    or else introduce a SWAP operation, which swaps the top two items on the stack:

    PUSH 5
    PUSH 4
    SWAP
    PUSH (POP / POP)
    

    or else compile the postfix so as to push in the opposite order:

    PUSH 4
    PUSH 5
    PUSH (POP/POP)