这是我们教授写的一篇教程,我无法理解它。我可以想出推导,但我只能通过分析推导来提出语法。
在这种情况下,“匹配”是指什么?
你能解释一下match_if,matched_stmt,unmatched_if如何用简单的单词:)?
The following is an unambiguous grammar for the problem:
stmt → if_stmt | nonif_stmt
if_stmt → matched_if | unmatched_if
matched_if → 'if' logical_expr 'then' matched_stmt 'else' matched_stmt
matched_stmt → mathced_if | nonif_stmt
unmatched_if → 'if' logical_expr 'then' stmt
| 'if' logical_expr 'then' matched_stmt 'else' unmatched_if
logical_expr → id '==' lit
nonif_stmt → assgn_stmt
assgn_stmt → id '=' expr
expr → expr '+' term | term
term → '(' expr ')' | id
id → 'A' | 'B' | 'C'
lit → '0' | '1' | '2'
Consider the following input:
if A == 0 then
if B == 1 then
C = A + B
else
B = C
Let us do a leftmost derivation for the input:
stmt
=> if_stmt
=> unmatched_if
=> 'if' logical_expr 'then' stmt
=> 'if' id '==' lit 'then' stmt
=> 'if' 'A' '==' lit 'then' stmt
=> 'if' 'A' '==' '0' 'then' stmt
=> 'if' 'A' '==' '0' 'then' if_stmt
=> 'if' 'A' '==' '0' 'then' matched_if
=> 'if' 'A' '==' '0' 'then' 'if' logical_expr 'then' matched_stmt 'else' matched_stmt
=> 'if' 'A' '==' '0' 'then' 'if' id '==' lit 'then' matched_stmt 'else' matched_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' lit 'then' matched_stmt 'else' matched_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' matched_stmt 'else' matched_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' nonif_stmt 'else' matched_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' assgn_stmt 'else' matched_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' id '=' expr 'else' matched_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' 'C' '=' expr '+' term 'else' matched_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' 'C' '=' term '+' term 'else' matched_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' 'C' '=' id '+' term 'else' matched_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' 'C' '=' 'A' + term 'else' matched_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' 'C' '=' 'A' + 'B' 'else' matched_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' 'C' '=' 'A' + 'B' 'else' nonif_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' 'C' '=' 'A' + 'B' 'else' assgn_stmt
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' 'C' '=' 'A' + 'B' 'else' id '=' expr
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' 'C' '=' 'A' + 'B' 'else' 'B' '=' expr
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' 'C' '=' 'A' + 'B' 'else' 'B' '=' term
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' 'C' '=' 'A' + 'B' 'else' 'B' '=' id
=> 'if' 'A' '==' '0' 'then' 'if' 'B' '==' '1' 'then' 'C' '=' 'A' + 'B' 'else' 'B' '=' 'C'
答案 0 :(得分:2)
“匹配”表示每个then
都与else
匹配。
if
语句没有必要匹配else
,但如果没有,则不能在匹配的if
语句中,因为这意味着一些else
匹配外部then
而非内部then
)。
所有语法都是上述形式化。
类似的问题是为普通的算术表达式编写一个语法,附加规则是你可以省去尾随的括号。 (所以你可以写(1+2*(1+2*(1+2
,例如。)这种语言显然是明确的,但是当你为它编写语法时,你需要处理不匹配的括号,因此需要处理包含无法匹配的括号的表达式。这与“匹配”这个词的使用相同·(并且解决方案有点类似)。