E -> E+T | E-T | T
T -> T*F | T/F | F
F -> i | (E)
How can I modify this grammar to allow an exponentiation operation ^
so that I can write i+i^i*i
? Since we know that order of operations is higher for ^
then all I know is that I must make it right associative.
In EBNF (Extended Backus-Naur Form), this could look as follows:
expr -> term [ ('+' | '-') term ]*
term -> factor [ ('*' | '/') factor ]*
factor -> base [ '^' exponent ]*
base -> '(' expr ')' | identifier | number
exponent -> '(' expr ')' | identifier | number
(taken from here)
Translated to your notation (no distinction between numbers and identifiers):
E -> E+T | E-T | T
T -> T*F | T/F | F
F -> F^X | B
B -> i | (E)
X -> i | (E)
One could merge "B" and "X" for the sake of clarity.
Both answers provided here are wrong. In these answers ^ associates to the left, when in fact it should associate to the right. The correct modified grammar should be:
E -> E+T | E-T | T
T -> T*X | T/X | X
X -> F^X | F //Note: it's F^X not X^F
F -> i | (E)
In this way, your grammar works as expected with an expression like :
a+b^c^d^e*f
Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With