I am working on a toy parser for arithmetic expressions and I am having trouble getting it to parse something like 2^-2. The reason for this is because my production rules look like:
Expression -> Expression ("+" | "-") Multiply | Multiply
... leave out a few rules for brevity ...
Unary -> ("+" | "-") Unary | Exponential
Exponential -> Primary ^ Exponential | Primary
Primary -> number | constant | "(" Expression ")"
I ordered the rules this way so that unary operators have a lower precedence than exponentiation, which I chose because most people seem to think that -2^2 is -4 not 4. The problem is that this requires that a Primary follows the ^ operator and -2 is not a Primary, it is a Unary, so it fails to parse.
Edit: For an expression like -2^-2 it seems most people's way of handling it would be to evaluate it as -(2^(-2)) which violate strict precedence rules because you are performing negation both before and after exponentiation. I am also not sure how to express that as a rule in a context-free grammar.
Edit Edit: I may have found a set of rules that accomplishes this. It seems to work so far with the desired order of operations and no ambiguities that I've detected so far...
expr -> expr "," add
| add
add -> add ("+" | "-") mult
| mult
mult -> mult ("*" | "/") exp
| exp
exp -> fact "^" exp
| ("+" | "-") exp
| fact
fact -> fact ("!" | "!!")
| primary
Primary -> "(" Expr ")"
| number
| constant
2^-2(with the interpretation $2^{-2}$) is a good idea to begin with and would much prefer writing that as2^(-2). Just consider how confusing2^-3^4looks – Hagen von Eitzen Oct 16 '23 at 16:482^-2into a calculator? Wolfram will gladly evaluate such an expression. Also, I would assume you example to be2^(-(3^4))– Chris_F Oct 16 '23 at 16:55-2^2=4when I think most people applying PEMDAS expect it to be -4. – Chris_F Oct 16 '23 at 17:57