Take a look at Theodore Norwell's recursive descent parsing
There he gives three ways to solve the problem.
1. The algorithm of the shunting yard.
2. A classic solution by factoring grammar.
3. Climbing priorities
Your problem is that your grammar requires several changes, for example,
Exrp: Term {[+ -] Expr} | Term
note the addition of { } around the [+-] Expr , indicating that they should be analyzed together and that there can be 0 or more.
Also by default you build the tree as
- / \ 2 + / \ 1 1
i.e. -(2,+(1,1))
when you have to build a tree for left associative operators with the same priority as
+ / \ - 1 / \ 2 1
i.e. +(-(2,1),1)
Since there are three ways to do this in a document, I will not disclose them here. Also, you mentioned that you are new to this, so you should get a good compiler book to understand the details that you will encounter when reading an article. Most of these methods are implemented in common programming languages ββand are available free of charge on the Internet, but keep in mind that many people do what you do and publish the wrong results.
The best way to check if you have this right, with the same test, using a multiple sequence of subtraction operations:
7-3-2 = 2
if you get
7-3-2 = 6 or something else
then this is wrong.
Guy coder
source share