Equation (expression) parser with precedence?

前端 未结 23 1963
遇见更好的自我
遇见更好的自我 2020-11-22 11:44

I\'ve developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &, *, /, etc) operators, unary (!) operators, and parenthesis.

<
23条回答
  •  面向向阳花
    2020-11-22 12:19

    It would help if you could describe the grammar you are currently using to parse. Sounds like the problem might lie there!

    Edit:

    The fact that you don't understand the grammar question and that 'you've written this by hand' very likely explains why you're having problems with expressions of the form '1+11*5' (i.e., with operator precedence). Googling for 'grammar for arithmetic expressions', for example, should yield some good pointers. Such a grammar need not be complicated:

     ::=  +  |
               -  |
              
    
     ::=  *  |
                /  |
               
    
     ::= x | y | ... |
                 (  ) |
                 -  |
                 
    

    would do the trick for example, and can be trivially augmented to take care of some more complicated expressions (including functions for example, or powers,...).

    I suggest you have a look at this thread, for example.

    Almost all introductions to grammars/parsing treat arithmetic expressions as an example.

    Note that using a grammar does not at all imply using a specific tool (a la Yacc, Bison,...). Indeed, you most certainly are already using the following grammar:

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

    (or something of the kind) without knowing it!

提交回复
热议问题