General
Material
Lecture 1
 Slides Practical Session
Lecture 2
 Slides Practical Session
Lecture 3
 Slides Practical Session
Lecture 4
 Slides Practical Session
Lecture 5
 Slides Practical Session

# DCGs for formal languages

Of course, DCGs cannot only be used to write grammars for natural languages, but also to specify grammars for formal languages. Formal languages are simply sets of strings. A simple example of a formal language is anbn. The language anbn consist of all strings made up from a's and b's that have the following form: the string must consist of an unbroken block of a#s of length n, followed by an unbroken block of b's of length n, and nothing else. So the strings ab, aabb, aaabbb and aaaabbbb all belong to anbn. (Note that the empty string belongs to too: after all, the empty string consists of a block of a's of length zero followed by a block of b's of length zero.) On the other hand, aaabb and aaabbba do not belong to anbn.

The following DCG accepts all strings that belong to the language anbn and rejects all those that don't. In other words, the DCG generates the language anbn.

```s --> [].
s --> l,s,r.

l --> [a].
r --> [b].
```
The first rule says that an s can be realized as nothing at all. The second rule says that an s can be made up of an l (for left) element, followed by an s, followed by an r (for right) element. The last two rules say that l elements and r elements can be realized as as and bs respectively.

The formal language aEven is very simple: it consists of all strings containing an even number of a's, and nothing else. Note that the empty string belongs to aEven. Write a DCG that generates aEven.
Solution

The formal language anb2mc2mdn consists of all strings of the following form: an unbroken block of a's followed by an unbroken block of b's followed by an unbroken block of c's followed by an unbroken block of d's, such that the a and d blocks are exactly the same length, and the c and d blocks are also exactly the same length and furthermore consist of an even number of c's and d's respectively. For example, the empty string, abbccd, and aaabbbbccccddd all belong to anb2mc2mdn. Write a DCG that generates this language.
Solution