开发者

Formula Parser with Brackets

开发者 https://www.devze.com 2023-01-05 14:10 出处:网络
I need to implement a simple formula parser. What I am doing is first create a postfix notation and then evaluating the postfix str开发者_如何学编程ing. Unfortunately, this algorithm doesn\'t allow br

I need to implement a simple formula parser. What I am doing is first create a postfix notation and then evaluating the postfix str开发者_如何学编程ing. 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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消