Context Free Grammar
Context Free Grammar
Context Free Grammar
Context free grammar is a formal grammar which is used to generate all possible strings in a given
formal language.
Language generated by context free grammar are known as context free language.
Production rules:
S → aSa
S → bSb
S → c
Now check that abbcbba string can be derived from the given CFG.
S ⇒ aSa
S ⇒ abSba
S ⇒ abbSbba
S ⇒ abbcbba
143
By applying the production S → aSa, S → bSb recursively and finally applying the production S →
c, we get the string abbcbba.
Context-free Languages
In formal language theory, a language is defined as a set of strings of symbols that may be
constrained by specific rules. Similarly, the written English language is made up of groups of
letters (words) separated by spaces. A valid (accepted) sentence in the language must follow
particular rules, the grammar.
A context-free language is a language generated by a context-free grammar. They are more
general (and include) regular languages. The same context-free language might be generated by
multiple context-free grammars.
The set of all context-free languages is identical to the set of languages that are accepted
by pushdown automata (PDA).
Here is an example of a language that is not regular (proof here) but is context-free:
\{a^nb^n | n \geq 0\}{anbn∣n≥0}. This is the language of all strings that have an equal number of
a’s and b’s.
In this notation, a^4b^4a4b4 can be expanded out to aaaabbbb, where there are four a’s and
then four b’s. (So this isn’t exponentiation, though the notation is similar).
CFLs are useful for describing “nested” structures (e.g., expressions with properly balanced
parentheses) that occur commonly in programming languages but are known to be not regular.
Type Name
0 Unrestricted Grammar
143
Chomsky Hierarchy
A->B;
A∈N i.e A is a non-terminal.
B∈V*(Any string).
Example –
S –> AB
A –> a
B –> b
2. Regular Grammar :
143
Example –
1. S –> ab.
2. S -> aS | bS | ∊
Restriction Less than Regular Grammar More than any other grammar
Right-hand The right-hand side of production has The right-hand side of production should be either left
Side no restrictions. linear or right linear.
Set Property Super Set of Regular Grammar Subset of Context Free Grammar
Complement They are not closed under complement Closed under complement
The range of languages that come The range of languages that come under RG is less
Range
under CFG is wide. than CFG.