Search code examples
infix-notationunary-operatorpostfix-notationbinary-operators

When converting from infix to postfix, how do you specify between a uniary and a binary +/-


Under this grammar:

^ + -  *  /  <  >  =  <= >=  and  or  not

I'm using a function (shunting-yard algorithm) to convert from infix to postfix and it works! Except it doesn't include the unary - meaning negate and the unary + which doesn't really do much of anything.

Once converted to post fix, a unary + will be a p and a unary - with be a m. For example:

3 + 3     ->     3 3 +
+3 + 3    ->     3 p 3 +
-(3-3)    ->     3 3 - m

So if I am reading an infix expression, how do I specify between a unary and binary plus and minus?


Solution

  • It seems to me that the following rule would apply.

    The first + or - following a non-operator is a binary operator. Subsequent occurrences (or an occurrence at the start of an expression) are unary.

    So, in your (and a couple of extra) examples:

    3 + 3             --> 3 binary+ 3
    + 3 + 3           --> unary+ 3 binary+ 3
    - ( 3 - 3)        --> unary- ( 3 binary- 3)
    -9--4             --> unary- 9 binary- unary- 4