Formal definition of Context-Free Grammer

 Here’s the formal definition of a Context-Free Grammar (CFG).


Definition

A Context-Free Grammar is a 4-tuple:

G=(V,Σ,R,S)G = (V, \Sigma, R, S)

where:

  1. VV — A finite set of nonterminal symbols (or variables).

  2. Σ\Sigma — A finite set of terminal symbols, such that VΣ=V \cap \Sigma = \varnothing

  3. RR — A finite set of production rules of the form

    AαA \rightarrow \alpha

    where AVA \in V and α(VΣ)\alpha \in (V \cup \Sigma)^* (that is, α\alpha

     is any finite string of terminals and/or nonterminals, possibly empty).

  4. SS — A distinguished element of VV, called the start symbol.


Key condition that makes it “context-free”:
In every production AαA \rightarrow \alpha, the left-hand side consists of exactly one nonterminal symbol A.

Characteristics of CFGs

  • Each production’s LHS must be a single nonterminal (unlike context-sensitive grammars).

  • They can describe nested and recursive structures, which are impossible for regular grammars.

  • Languages generated by CFGs are called Context-Free Languages (CFLs).

Example

Let:

  • V={S}

  • Σ={a,b}\Sigma = \{a, b\}

  • R:SaSb  εR: S \rightarrow aSb \ | \ \varepsilon

  • SS is the start symbol.

This grammar generates strings with equal numbers of a’s followed by b’s:

L={anbn  n0}L = \{ a^n b^n \ | \ n \ge 0 \}

Derivation example:

SaSbaaSbbaaεbb=aabbS \Rightarrow aSb \Rightarrow aaSbb \Rightarrow aa\varepsilon bb = aabb

Parse Trees

parse tree shows how a string is generated from the start symbol.

For the earlier grammar 

SaSb  εS \rightarrow aSb \ | \ \varepsilon, the string "aabb" has:
S /|\ a S b /|\ a S b | ε

A Worked Example

Problem: Create a CFG for

L={w{a,b}  w is a palindrome}L = \{ w \in \{a, b\}^* \ | \ w \text{ is a palindrome} \}

Solution:

SaSa  bSb  a  b  εS \rightarrow aSa \ | \ bSb \ | \ a \ | \ b \ | \ \varepsilon

Derivation for "abba":

SaSaabSbaabεba=abbaS \Rightarrow aSa \Rightarrow abSb a \Rightarrow ab\varepsilon b a = abba

Comments

Popular posts from this blog

Theory Of Computation PCCST302 KTU Semester 3 BTech 2024 Scheme

Non deterministic Finite Automata NFA

Example DFAs University Questions