Search code examples
mathbnf

Representing simple mathematics using BNF


I have written the following BNF "code", which attempts to describe simple mathematics using BNF. The issue I am having is that I have no idea how to add parentheses (brackets).

Digit ::= "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9";
Digits ::= <Digit>|<Digit><Digit>;
Number ::= <Digits>|<Digits>.<Digits>;

Addition ::= <Value> + <Value>;
Subtraction ::= <Value> - <Value>;
Multiplication ::= <Value> * <Value>;
Division ::= <Value> / <Value>;
Value ::= <Number>|<Addition>|<Subtraction>|<Multiplication>|<Division>;

The other issue is that I'm not sure that the BNF is 100% correct, as the Value "description" doesn't look right to me.


Solution

  • Digit ::= "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9";
    Digits ::= <Digit>|<Digit><Digits>;
    Number ::= <Digits>|<Digits>.<Digits>;
    Operator ::= "+" | "-" | "*" | "/"
    Bracket_Left ::= "("
    Bracket_Right ::= ")"
    Value ::= <Number>|<Bracket_Left><Value><Bracket_Right>|<Value><Operator><Value>
    

    Maybe not the most elegant solution, but should work. Always keep in mind the power of recursion.