...

/

Context-free Grammars and Derivations

Context-free Grammars and Derivations

Learn about context-free grammar and look at some examples.

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), VV, one of which is a start variable.
  • An alphabet, Σ\Sigma, of terminal symbols.
  • A set of production rules of the form vsv\rightarrow s, where vVv\in V and s(VΣ)s\in (V\cup\Sigma)^*, 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 {anbn    n>0}\{a^nb^n\;|\;n>0\}:

As a reminder, using the alternation symbol “\mathbf{|}” 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 abab, which occurs by choosing the second rule above. To generate the language {anbn    n0}\{a^nb^n \;|\; n\geq 0\}, we would replace abab with the empty string.


To generate the language {anb2n    n0}\{a^nb^{2n} \;|\; n\geq 0\}, we generate two bb’s for every aa:

We derive the string aabbbbaabbbb like this:


To construct a CFG for the language {aibj    ij}\{a^ib^j\;|\;i\neq j\} ...

Access this course and 1400+ top-rated courses and projects.