what is an ambiguous context free grammar?

大憨熊 提交于 2019-12-10 20:53:36

问题


I'm not really very clear on the concept of ambiguity in context free grammars. If anybody could help me out and explain the concept or provide a good resource I'd greatly appreciate it.


回答1:


T * U;

Is that a pointer declaration or a multiplication? You can't tell until you know what T and U actually are.

So the syntax of the expression depends on the semantics (meaning) of the expression. That's not context-free -- in a context-free language, that could only be one thing, not two. (This is why they didn't let expressions like that be valid statements in D.)

Another example:

T<U> V;

Is that a template usage or is that a greater-than and less-than operation? (This is why they changed the syntax to T!(U) V in D -- parentheses only have one use, whereas carets have another use.)




回答2:


How would you parse this:

if condition_1 then if condition_2 then action_1 else action_2

To which "if" does the "else" belong?

In Python, they are:

if condition_1:
    if condition_2:
        action_1
    else:
        action_2

and:

if condition_1:
    if condition_2:
        action_1
else:
    action_2



回答3:


Consider an input string recognized by context-free grammar. The string is derived ambiguously if it has two or more different leftmost derivations, or parse trees of you wish. A grammar is ambiguous if it generates strings ambiguously. For example, the grammar S -> E + E | E * E is an ambiguous grammar as it derives the string x + x * x ambiguously, in other words there are more than one parse tree to represent the expression (there are two actually). The grammar can be made non-ambiguous by changing the grammar to:

E -> E + T | T

T -> T * F | F

F -> (E) | x

The refactored grammar will always derive the string unambiguously, i.e. the derivation will always produce the same parse tree.



来源:https://stackoverflow.com/questions/6035451/what-is-an-ambiguous-context-free-grammar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!