Note that there are some explanatory texts on larger screens.

plurals
  1. POEquation (expression) parser with precedence?
    primarykey
    data
    text
    <p>I've developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &amp;, *, /, etc) operators, unary (!) operators, and parenthesis.</p> <p>Using this method, however, leaves me with everything having the same precedence - it's evaluated left to right regardless of operator, although precedence can be enforced using parenthesis.</p> <p>So right now "1+11*5" returns 60, not 56 as one might expect.</p> <p>While this is suitable for the current project, I want to have a general purpose routine I can use for later projects.</p> <p><strong>Edited for clarity:</strong></p> <p>What is a good algorithm for parsing equations with precedence?</p> <p>I'm interested in something simple to implement and understand that I can code myself to avoid licensing issues with available code.</p> <p><strong>Grammar:</strong></p> <p>I don't understand the grammar question - I've written this by hand. It's simple enough that I don't see the need for YACC or Bison. I merely need to calculate strings with equations such as "2+3 * (42/13)".</p> <p><strong>Language:</strong></p> <p>I'm doing this in C, but I'm interested in an algorithm, not a language specific solution. C is low level enough that it'll be easy to convert to another language should the need arise.</p> <p><strong>Code Example</strong></p> <p>I posted the <a href="http://www.ubasics.com/simple_c_equation_parser" rel="noreferrer">test code for the simple expression parser</a> I was talking about above. The project requirements altered and so I never needed to optimize the code for performance or space as it wasn't incorporated into the project. It's in the original verbose form, and should be readily understandable. If I do anything further with it in terms of operator precedence, I'll probably choose <a href="https://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/783132#783132">the macro hack</a> because it matches the rest of the program in simplicity. If I ever use this in a real project, though, I'll be going for a more compact/speedy parser.</p> <p><strong>Related question</strong> </p> <blockquote> <p><a href="https://stackoverflow.com/questions/114586/smart-design-of-a-math-parser">Smart design of a math parser?</a></p> </blockquote> <p>-Adam</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload