1

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

Chris_F
  • 175
  • I don't think allowing 2^-2 (with the interpretation $2^{-2}$) is a good idea to begin with and would much prefer writing that as 2^(-2). Just consider how confusing 2^-3^4 looks – Hagen von Eitzen Oct 16 '23 at 16:48
  • 1
    @HagenvonEitzen But are most people going to expect to receive a syntax error when they enter 2^-2 into a calculator? Wolfram will gladly evaluate such an expression. Also, I would assume you example to be 2^(-(3^4)) – Chris_F Oct 16 '23 at 16:55
  • Why is there a need to distinguish between unary and primary? – Natalie Clarius Oct 16 '23 at 17:37
  • @NatalieClarius Well, if unary operators were handled by primary, then negation would always happen before exponents and -2^2=4 when I think most people applying PEMDAS expect it to be -4. – Chris_F Oct 16 '23 at 17:57
  • But are most people going to expect to receive a syntax error when they enter 2^-2 into a calculator? --- Not if you enter $-2$ via "2 followed by the plus/minus sign". I think questions like these are so dependent on the calculator or other device (e.g. Excel spreadsheet, smart phone, etc.) and era (e.g. 30 years ago vs. now vs. 30 years from now) to be of little widespread value or lasting relevance. – Dave L. Renfro Oct 16 '23 at 19:46
  • @Chris_F - Can you group negation and exponentiation together, evaluating them from right to left? – mr_e_man Oct 16 '23 at 21:11
  • Also think about other functions, e.g. 2^cos 30 or cos 2^30. – mr_e_man Oct 16 '23 at 21:12

0 Answers0