![]() |
VOOZH | about |
A grammar consists of one or more variables that represent classes of strings (i.e., languages) . There are rules that say how the strings in each class are constructed. The construction can use :
A context-free grammar (CFG) is a formal system used to describe a class of languages known as context-free languages (CFLs). Purpose of context-free grammar is:
A GFG (or just a grammar) G is a tuple G = (V, T, P, S) where
A grammar is said to be the Context-free grammar if every production is in the form of:
G -> (VβͺT)* , where G β V
- V (Variables/Non-terminals): These are symbols that can be replaced using production rules. They help in defining the structure of the grammar. Typically, non-terminals are represented by uppercase letters (e.g., S, A, B).
- T (Terminals): These are symbols that appear in the final strings of the language and cannot be replaced further. They are usually represented by lowercase letters (e.g., a, b, c) or specific symbols.
- The left-hand side can only be a Variable, it cannot be a terminal.
- But on the right-hand side here it can be a Variable or Terminal or both combination of Variable and Terminal.
The above equation states that every production which contains any combination of the 'V' variable or 'T' terminal is said to be a context-free grammar.
A CFG is defined by:
| Model | Description |
|---|---|
| Finite Automata | Accept strings via computation (accept/reject). |
| Regular Expressions | Match strings by describing their structure. |
| CFG | Generate strings via recursive replacement. |
Suppose we want to describe all legal arithmetic expressions using addition, subtraction, multiplication, and division.
Here is one possible :
CFG:
E β int
E β E Op E
E β (E)
Op β +
Op β -
Op β *
Op β /
E
β E Op E
β E Op int
β int Op int
β int / int
When creating CFGs:
Examples:
1. Palindromes over {a, b}:
S β Ξ΅ | a | b | aSa | bSb
2. Balanced Parentheses:
S β Ξ΅ | (S) | SS
The language L(G) generated by a CFG G is: L(G)={ ΟβΞ£*β£SββΟ}
| Property | Regular Languages | Context-Free Languages |
|---|---|---|
| Power | Limited | More expressive |
| Memory Requirements | Finite | Unbounded recursion |
| Definable Structures | Simple patterns (e.g., repetition) | Nested structures (e.g., palindromes, balanced parentheses) |
Productions such as:
a->bSa, or
a->ba is not a CFG as on the left-hand side there is a terminal which does not follow the CFGs rule.
But we can construct it by :
Lets consider the string "aba" and and try to derive the given grammar from the productions given. We start with symbol S, apply production rule S->bSa and then (S->a) to get the string "aba".
In the computer science field, context-free grammars are frequently used, especially in the areas of formal language theory, compiler development, and natural language processing. It is also used for explaining the syntax of programming languages and other formal languages.