I'm trying to create an unambiguous grammar for a calculator that uses $+$, $-$, $*$, $/$ and $()$. From watching videos and reading articles online, I understand how to create the grammar with $+$, $*$, $()$ (or 3 different precedences).

i.e. $E \to E + E \mid E * E \mid (E) \;\mid \;\text{num}$

$$\begin{align} E &\to E + F \mid T\\ T &\to T * F \mid F\\ F &\to(E)\;|\; \text{num}\\ \end{align}$$

How would I include $-$ and $/$ in this? Would this approach be correct (unambiguous)?

$$\begin{align} E &\to E + F \mid E - F \mid T\\ T &\to T * F \mid T / F \mid F\\ F &\to(E)\;|\; \text{num}\\ \end{align}$$

  • $\begingroup$ Unrelated: Does 1+2*3 parse the way you are hoping it will? $\endgroup$ – D.W. Apr 13 at 2:51
  • $\begingroup$ Is the resulting grammar still unambiguous? Does it parse sample input correctly? If so, the approach is correct. $\endgroup$ – Yuval Filmus Apr 13 at 8:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.