How can I modify my Shunting-Yard Algorithm so it accepts unary operators?

后端 未结 6 718
眼角桃花
眼角桃花 2020-12-09 16:25

I\'ve been working on implementing the Shunting-Yard Algorithm in JavaScript for class.

Here is my work so far:

var userInput = prompt(\"Enter in a m         


        
6条回答
  •  暖寄归人
    2020-12-09 16:38

    I could solve this problem by modifying unary operators('+' and '-') to distinguish them from the binary ones.

    For example, I called the unary minus 'm' and unary plus 'p', making them right-assocative and their precedence equal to the exponent operator('^').

    To detect if the operator is unary I simply had to check if the token before the operator was an operator or an opening bracket.

    This is my implementation in C++:

            if (isOperator(*token))
            {
                if (!isdigit(*(token - 1)) && *(token - 1) != ')')   // Unary check
                {
                    if (*token == '+')
                        *token = 'p';        // To distinguish from the binary ones
                    else if (*token == '-')
                        *token = 'm';
                    else
                        throw;
                }
    
                short prec = precedence(*token);
                bool rightAssociative = (*token == '^' || *token == 'm' || *token == 'p');
    
                if (!operators.empty())
                {
                    while (prec < precedence(operators.top()) || (prec == precedence(operators.top()) && !rightAssociative))
                    {
                        rpn += operators.top();
                        operators.pop();
    
                        if (operators.empty())
                            break;
                    }
                }
                operators.push(*token);
            }
    

    Here operators is a stack and token is an iterator to the infix expression string

    (This just the operator handling part)

提交回复
热议问题