Reputation: 9879
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 +
?
Upvotes: 6
Views: 1566
Reputation: 1
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!!!)
Upvotes: 0
Reputation: 58518
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.
Upvotes: 9