3

Given the infix expression -190 + 20, what would the correct result look like as RPN?

-190 + 20 == -190 20 + ?

or..

-190 + 20 == 190 - 20 + ?

Are the rules for unary operators (negative) the same as other operators, but just a right associative property, and higher priority?

Similarly an expression like: -(9 + 9)

Would be? -(9 + 9) = 9 - 9 +?

GN.
  • 8,672
  • 10
  • 61
  • 126

2 Answers2

5

In a typical RPN language, you can't have the same token - interpreted as either a unary or binary operator depending on context, because there is no context. It has to always be one or the other. So commonly - is kept as the binary subtraction operator, and some other token is used for the unary negation operator. Forth, for instance, called it NEGATE. Thus in Forth, your -190 + 20 could be coded as 190 NEGATE 20 +, and your -(9+9) as 9 9 + NEGATE.

Forth could also parse negative numbers, so your -190 + 20 could also be coded -190 20 +. However the - is not an operator in this instance, but merely part of the single token -190. The only operator being used in this example is +.

If you write 190 - 20 + in a typical RPN language, you will get a stack underflow (or else whatever happened to be on the stack, minus 190, plus 20) since - is unconditionally interpreted as the binary operator.

RPN has no concept of precedence nor associativity - those serve to resolve ambiguity in the evaluation of expressions, and RPN has no such ambiguity in the first place.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
  • Thanks. What I mean is, during the shunting of infix to postfix, when the lexer identifies a token as a unary minus — (I've seen it suggested that) the unary minus should be set as right assoc, and have the highest precedence (i.e. is pow operator is 3, unary minus should be 4)? – GN. Nov 17 '20 at 02:29
  • Perfect answer from Eldredge. [Here](http://www.7th-stone.com/index.php?id=14) is a _Forth_ -like interpreter to play with. – Kaplan Dec 19 '20 at 10:26
0

unary minus should be no issue. If the stack has only a single operand after meeting a minus then it is unary. One online RPN generator generates a gratis 0, so -b becomes 0-b. But surely

    (-2)*(-3-5) should just be 2-3-5-*. 
    and
    -190 + 20 ==> 190-20+
    -(9 + 9) ==> 9 9 + -
    while
    (-a)*((-b)-(-c)) ==> a- b- c- -* (that one may need checking!!!)
laogui32
  • 1
  • 2