100 likes | 272 Views
Discrete Structure. Li Tak Sing( æŽå¾·æˆ ). From grammar to inductive definition. Consider the following grammar: S ï‚®ïŒ|aB B ï‚®b|bB Basis: ïŒ, abL(G) Induction: if ay  L(G), then aby  L(G). Constructing grammars. {a n |n N} Sï‚®ïŒ|aS {a n b n |n N} S ï‚®ïŒ|aSb {(ab) n |nN} S ï‚®ïŒ|abS.
E N D
Discrete Structure Li Tak Sing(李德成)
From grammar to inductive definition • Consider the following grammar: • S|aB • B b|bB • Basis: , abL(G) • Induction: if ay L(G), then aby L(G).
Constructing grammars • {an|nN} • S|aS • {anbn|n N} • S |aSb • {(ab)n|nN} • S |abS
Combining grammars • Suppose M and N are languages whose grammars have disjoint sets of non-terminals. Suppose also that the start symbols for the grammars of M and N are A and B respectively. Then we have the following new languages and grammars: • Union rule: the language MN starts with the two productions: SA|B • Product Rule: the language MN starts with the productions: S AB • Closure Rule: The language M* starts with the productions: S AS|
Examples • Write the grammar for each of the following languages. • {anbcm|m,nN} • {, a, ab, aab, aaab, ....} • {a, ba, bba, bbba, ....} • {anbn|n N}* • {anbn|n N}{cn|n1}
Meaning and ambiguity • A grammar is said to be ambiguous if its language contains some string that has two different parse trees. This is equivalent to saying that some string has two distinct leftmost derivations or that some string has two distinct rightmost derivations.
Ambiguity • Consider the grammar. • Ea|b|E-E • The string a-b-a has the following distinct derivations. • EE-E a-E a-E-E a-b-E a-b-a • E E-E E-E-E a-E-E a-b-E a-b-a • The former one has the meaning of a-(b-a) • The latter one has the meaning of (a-b)-a
Removing the ambiguity • If we change the grammar as this: • E E-T|T • T a|b • In the above grammar, T can only be replaced by a or b. So only the right operand can be further expands to another expression that have -. So a-b-a will only be expanded to have the meaning of (a-b)-a
Ambiguity • Show that each of the following grammers is ambiguous. In other words, find a string that has two different parse trees (equivalently, two different leftmost derivations or two different rightmost derivations) • Sa|SbS. • S abB|AB and A |Aa and B |bB. • S aS|Sa|a • S aS|Sa|b • S Ab|A and A b|bA
More Examples • Find grammars for the following languages: • {anbmcmdn| m,n N} • {anbmcdn| m,n N} • {anbmcmd| m,n N} • {abmcmd| m,n N} • abmcdm| m N}