Generate syntax tree for simple math operations

后端 未结 4 1461
故里飘歌
故里飘歌 2020-12-31 19:27

I am trying to generate a syntax tree, for a given string with simple math operators (+, -, *, /, and parenthesis). Given the string \"1 + 2 * 3\":

It shou

4条回答
  •  半阙折子戏
    2020-12-31 19:57

    The thing to do is to use a parser generator like flex or ANTLR (searching at google will find one for your language).

    But if you are doing this for fun or to learn how parsers work, look up wikipedia for recursive descent parser.

    A simple recursive descent parser can be easily made for simple expressions like this. You can define the grammar as:

     ::=  |   
     ::=  |   
     ::= (  ) |  
     ::= + | -
     ::= * | /
    

    Notice that by making the rule for contain the rule for this grammar makes sure all multiplication/division operations occur lower in the parse tree than any addition/subtraction. This ensures those operations are evaluated first.

提交回复
热议问题