Verify Mathematical Equation c++ [closed]

大城市里の小女人 提交于 2019-12-02 13:03:16

问题


I am currently trying to build a very simple compiler. I have created a function that converts a mathematical equation in infix notation to RPN using the shunting-yard algorithm however I have encountered a problem. I did not include error checking in my conversion function so I was wondering if there was a simple way to check if a function in infix notation is in correct infix notation syntax. This would enable me to keep my current conversion function without obscuring it with error checking.


回答1:


If your expressions only consist of parentheses, values (constants and/or identifiers), and prefix, postfix and infix operators, then there are two error conditions you need to check:

  1. The parentheses must match. It's hard not to notice this with the shunting yard algorithm, because there is a point in the algorithm where an open parenthesis is popped off the stack when a close parenthesis is encountered in the input. If you overpop the stack or you don't pop the entire stack at end of input, then the parentheses didn't balance.

  2. The tokens must conform to the following simple regular expression:

    PRE* VAL POST* ( INFIX PRE* VAL POST* )*
    

    where

    • PRE is a prefix operator or an (
    • POST is a postfix operator or a )
    • VAL is a value: a constant or an identifier

That actually reduces to a two-state state machine: the initial state (state 0) could be called "expecting value" and the other state (state 1) could be called "expecting operator". Only state 1 is accepting, and the transitions are as follows:

State 0:
    PRE   → State 0
    VAL   → State 1

State 1:
    POST  → State 1
    INFIX → State 0

All other transitions are to an error.

It's often necessary to implement this state machine in order to properly deal with unary minus (and other operators which could be prefix or infix), and it is, in any event, very simple to integrate into your input handling.



来源:https://stackoverflow.com/questions/26921944/verify-mathematical-equation-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!