Unambiguous grammar for exponentiation operation

前端 未结 3 1225
故里飘歌
故里飘歌 2020-12-04 00:15
E -> E+T | E-T | T
T -> T*F | T/F | F
F -> i | (E)

How can I modify this grammar to allow an exponentiation operation ^ so th

3条回答
  •  情歌与酒
    2020-12-04 00:32

    In EBNF (Extended Backus-Naur Form), this could look as follows:

    expr -> term [ ('+' | '-') term ]*
    term -> factor [ ('*' | '/') factor ]*
    factor -> base [ '^' exponent ]*
    base -> '(' expr ')' | identifier | number
    exponent -> '(' expr ')' | identifier | number
    

    (taken from here)

    Translated to your notation (no distinction between numbers and identifiers):

    E -> E+T | E-T | T
    T -> T*F | T/F | F
    F -> F^X | B
    B -> i | (E)
    X -> i | (E)
    

    One could merge "B" and "X" for the sake of clarity.

提交回复
热议问题