tags:

views:

100

answers:

2

hi, i am currently doing a java simple calculator parser, that will deal very simply with + and - operators only and numbers only and also ( and ) , i have read about

http://scriptasylum.com/tutorials/infix_postfix/algorithms/postfix-evaluation/index.htm

http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm

and i am wondering if the brackets can be applied to the above mentioned way of creating a calculator parser?

+4  A: 

The beauty of the postfix/prefix notation is that you do NOT need the brackets. Brackets are used in infix notation because there are ambiguities, e.g:

a + b - c

This can mean either of the following:

(a + b) - c
a + (b - c)

However, in postfix notation, they are clearly different:

a b + c -
a b c - +

There is no need for parantheses/brackets to enforce evaluation order in postfix notation.

See also


Conversion from infix

You can take an expression in infix notation with parantheses and convert it to postfix notation, obeying operator precedence. One such algorithm is Edsger Dijkstra's stack-based "shunting-yard algorithm".

See also

polygenelubricants
A: 

If you are only concerned with the simple math operators + and - which are commutative then you probably do not need to care about parenthesis which usually enforce the order of computation.

Your calculator might only need to be a simple parser and accumulator that ignores parenthesis if present - unless I'm missing something about the intended meaning of the parenthesis

bjg
I'm not sure what commutativity has to do with the issue. Especially since `a - b` is not the same as `b - a`. That is, `-` is NOT commutative.
polygenelubricants
My bad. What I meant to say was that the + and - ops are associative
bjg
Guess he meant to say (a + b) - c = a + (b - c), for + and - operations parenthesis are meaningless (ignoring rounding errors for floating point operations)
vickirk