What is the smartest way to design a math parser? What i mean is a function that takes a math string (like: "2 + 3 / 2 + (2 * 5)") and returns the calculated value? I've developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &, *, /, etc) operators, unary (!) operators, and parenthesis.
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. 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)".
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.
If you want to solve this problem, you really want a recursive descent parser. To get precedence you need to think recursively, for example, using your sample string, 1+6*5 to do this manually, you would have to read the 1, then see the plus and start a whole new recursive parse "session" starting with 6... and make sure to parse the 6 * 5 into its own factor, yielding a parse tree with 1 + (6 * 5).
This is a nice hobby project, if you want a good, tested, proven math parser, then you can use a commercial alternative like Bestcode.com parser libraries: Math Parser for C++, Math Parser for Java, Math Parser for Delphi, Math Parser for .NET, for COM and Math Parser for PHP.
|