Archived

This topic is now archived and is closed to further replies.

Alpha_ProgDes

Notation: Postfix = good, Prefix = ??? Simply, can someone help me figure this out?

Recommended Posts

I'm having a problem (why i don't know) of converting infix to prefix and prefix to infix. as well as just solving a prefix equation correctly. here's an example: / + - A / B C E + A B do you read it from left to right or right to left? [edited by - Alpha_ProgDes on May 3, 2003 7:56:55 PM]

Share this post


Link to post
Share on other sites
When thinking in terms of pushing and popping operands on a stack, you should read from right to left (which is why postfix notation is somewhat more common).


How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites
Prefix notation is the operator followed by its operands. These are all binary operators, so each operator takes two operands. Take your data and insert delimiting parentheses:

/ + - A (/ B C) E (+ A B)

This is the obvious step. Each of these quantities reduces to one value, so add more parentheses:

/ + (- A (/ B C)) E (+ A B)
/ (+ (- A (/ B C)) E) (+ A B)
(/ (+ (- A (/ B C)) E) (+ A B))

Then take each one and put the operator in the middle instead of in front:

(/ (+ (- A (B / C)) E) (A + B))
(/ (+ (A - (B / C)) E) (A + B))
(/ ((A - B/C) + E) (A + B))
(((A - B / C) + E) / (A + B))

Remove the superfluous parentheses:
(A - B / C + E) / (A + B)

This is the easiest way I''ve found to convert from one notation to another manually. The easiest way to convert in a computer is a lot different.

Share this post


Link to post
Share on other sites
For a quick and dirty prefix parser, do the following:

gettoken()
{
eat a token
if it''s an operator, lhs = gettoken(), rhs = gettoken(), return operator(lhs,rhs)
if it''s a constant or variable, return it;
}

Share this post


Link to post
Share on other sites