什么时候在EBNF中使用括号?

时间:2010-09-24 20:00:45

标签: bnf

如果你有这样的语法:

<assign> → <id> = <expr> 
<id> → A | B | C 
<expr> → <expr> + <term> 
         |  <term> 
<term> → <term> * <factor> 
         |  <factor> 
<factor> → ( <expr> ) 
          | <id>

然后句子A = B + C * A,你得到这个最左边的推导:

<assign> => <id> = <expr> 
         => A = <expr> 
         => A = <expr> + <term> 
         => A = <term> + <term> 
         => A = <factor> + <term> 
         => A = <id> + <term> 
         => A = B + <term> 
         => A = B + <term> * <factor> 
         => A = B + <factor> * <factor> 
         => A = B + <id> * <factor> 
         => A = B + C * <factor> 
         => A = B + C * <id> 
         => A = B + C * A

但是A = B +(C * A)怎么样?

2 个答案:

答案 0 :(得分:2)

  
    

A = B +(C * A)?

  

前五个步骤,与上述相同,然后......

     => A = B + <term>  
     => A = B + <factor>    
     => A = B + ( <expr>) 
     => A = B + ( <term> )  
     => A = B + ( <term> * <factor> ) 
     => A = B + ( <factor> * <factor> ) 
     => A = B + ( <id> * <id> ) 
     => A = B + (  C   *   A  )

答案 1 :(得分:0)

( C * A )不需要paren,因为*具有更高的优先级。您可以在A = B * ( C + B )中找到一个案例。

您在最后两行中没有看到它,因为<factor>将变为<term> + <term><id>。在这种情况下,没有+所以它必须是<id>