76.3k views
2 votes
Create an unambiguous grammar which generates basic mathematical expressions (using numbers and the four operators +, -, *, /). Without parentheses, parsing and mathematically evaluating expressions created by this string should give the result you'd get while following the order of operations. For now, you may abstract "number" as a single terminal, n. In the order of operations, * and / should be given precedence over + and -. Aside from that, evaluation should occur from left to right. So 8/4*2 would result in 4, not 1.

1 Answer

2 votes

Answer:

Step-by-step explanation:

Let G denote an unambiguous Grammar capable of producing simple mathematical expressions, involving operators +,-,*,/. These operators are left associative (which ensures left to right evaluation). S is the start symbol of the Grammar i.e. the production starts from S. n denotes a number and is a terminal i.e. we can't produce anything further from n. Then, the solution is as follows :

S → S + T |S - T | S

T→T | F | T*F|F

F → n

Here, S, T and F are variables. Note that /,* have been given precedence over +,-.

User Sourygna
by
4.6k points