Context-free Grammars and Derivations
Learn to define context-free grammars (CFGs) and perform derivations to generate languages in computation. This lesson covers CFG components, example grammars for balanced strings, palindromes, and languages with symbol count constraints. Discover how CFGs model complex language structures and support automata theory. Understand closures under operations like concatenation and how CFGs represent important computational languages.
We'll cover the following...
Let’s formally define context-free grammar (CFG).
Context-free grammar
A context-free grammar is a formal grammar consisting of the following:
- A set of variables (i.e., a nonterminal alphabet), , one of which is a start variable.
- An alphabet, , of terminal symbols.
- A set of production rules of the form , where and , a string of terminals and/or variables.
Let’s look at some illustrations of CFGs for some of the languages.
Examples of CFGs
The following CFG generates the language :
As a reminder, using the alternation symbol “” allows us to combine all the productions for a given variable on a single line. This grammar can also be expressed as:
The smallest string in the language is , which occurs by choosing the second rule above. To generate the language , we would replace with the empty string.
To generate the language , we generate two ’s for every :
We derive the string like this:
To construct a CFG for the language ...