views:

54

answers:

3

Hi folks,

I need to implement a simple formula parser. What I am doing is first create a postfix notation and then evaluating the postfix string. Unfortunately, this algorithm doesn't allow brackets i.e. (2+3)*a. Anyone knows how to extend the algorithm to allow brackets?

Thanks in advance,
Frank

+1  A: 

Perhaps this article can be of help?

http://www.go4expert.com/forums/showthread.php?t=1693

/Fridden

Fridden
+4  A: 

The whole point of postfix notation is to eliminate the brackets in infix notation so that you can evaluate the expression more easily. If your current algorithm doesn't allow brackets in the infix expression, then you're using a bad algorithm.

The shunting yard algorithm will allow you to convert from infix to postfix even if the infix version has brackets.

IVlad
Hi Vlad, I found that the algorithm I used is a "stripped-down" shunting yard. With the infos from the wikipedia, I was able to adapt it properly. Many thanks!
Aaginor
A: 

As an alternative, the grammar for arithmetic expressions is quite simple and you can easily implement a recursive descent parser that evaluates the expression for you.

The grammar would look something like this:

<expression> ::= <term> <add_sub> <expression>
<term> ::= <factor> <mul_div> <term>
<factor> ::= '(' <expression> ')' | <number>
<add_sub> ::= '+' | '-'
<mul_div> ::= '*' | '/'

(you have to define to be integers, floating point values, fractions etc. depending on your needs)

The above grammar takes care of brackets and operator precedence

MAK