# Grammar!

This topic is 4058 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I this exercise in Compilers: Principles, Techniques, and Tools: Construct an unambiguous context-free grammar for arithmetic expressions in postfix notation. Quick answer: expr := expr expr op | number op := + | - | * | / Afterwards, though, I attempted to get rid of left recursion, and got completely stuck. It seems to make it very difficult that the first number can be used in a subexpression. Is there a remotely simple way, or am I just blanking on this?

##### Share on other sites
There are multiple simple ways. The main important bit to realize is that you'll always have number on the left, and it won't be the terminal case, either. Not always, anyways. There will still be right recursion of course.

boost::spirit's FAQ also describes eliminating left recursion for a rather generalized case -- if you want to figure it out without me downright giving you the answer(s). Theirs also eliminates RHS recursion, however, something I doubt you need to do, and may or may not want to do. The multiple ways I'm thinking of didn't involve removing RHS recursion.

##### Share on other sites
Thanks, I managed to come up with

expr := part part op
part := term part op | term

Which seems to work for the most part.

##### Share on other sites
Quote:
 Original post by GameDev DoctorThanks, I managed to come up withexpr := part part oppart := term part op | termWhich seems to work for the most part.

We can simplify this a slight bit to one of the following:

expr := term expr op | term
expr := term (expr op)?

Which were the ones I were thinking of :).

1. 1
2. 2
3. 3
Rutin
22
4. 4
frob
17
5. 5

• 9
• 33
• 13
• 13
• 10
• ### Forum Statistics

• Total Topics
632580
• Total Posts
3007192

×