I have to implement an expression calculator without using stacks. I'm just really confused as to how to start this. If anyone could explain to me what I'm supposed to do, I would really appreciate it. I realize this isn't the best question, nor is it specific, but I'm just having a really hard time even getting started.
I just don't understand (at all) how I'm supposed to use recursion to implement this calculator. How am I supposed to use the m_exp l_op h_op etc that they defined? I just don't understand at all, sorry for the lack of better words :(
Given the expression 2.3 * 4 - 7.8 / 9
, you want to build a parse tree:
"-"
._____|_____.
| |
"*" "/"
.__|__. .__|__.
| | | |
2.3 4 7.8 9
It can be generated by recursively applying the definitions given in the last part of the exercise:
Start: EXP
Rule 4: EXP L_OP M_EXP
Rule 5: M_EXP "-" M_EXP
Rule 2: M_EXP H_OP M_EXP "-" M_EXP H_OP M_EXP
Rule 6: M_EXP "*" M_EXP "-" M_EXP "/" M_EXP
Rule 1: 2.3 * 4 - 7.8 / 9
A way of approaching this is making a series of functions that handle each rule:
void m_exp();
void exp();
etc...
Each of these functions will try to match the next part of the input, and update some global variables accordingly. Wikipedia has a great article about recursive descent parsers, which includes a C example.
How exactly am I supposed to "recurisvely apply the definitions given in the last part of the exercise", the stuff you wrote?
Here is an excerpt from the aforementioned article, slightly modified:
// Implements Rule 1
void num(void) {
// Reads a number
}
// Implements Rule 2
void m_exp(void) {
num();
while (sym == '*' || sym == '/') {
getsym();
num();
// Does more work...
}
}
// Implements Rule 4
void exp(void) {
m_exp();
while (sym == '+' || sym == '-') {
getsym();
m_exp();
// Does more work...
}
}
Rules 5 and 6 are already built-in. Rule 3 is the entry point.
Here, the [tail recursion] has been replaced by loops. Note how exp
calls m_exp
many times, and m_exp
does the same with num
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments