# 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
*a ^{n}b^{n}*. The language

*a*consist of all strings made up from

^{n}b^{n}*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

*a*. (Note that the empty string belongs to too: after all, the empty string consists of a block of

^{n}b^{n}*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

*a*.

^{n}b^{n}
The following DCG accepts all strings that belong to the
language *a ^{n}b^{n}* and rejects all those
that don't. In other words, the DCG generates the language

*a*.

^{n}b^{n}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
*a ^{n}b^{2m}c^{2m}d^{n}*
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

*a*. Write a DCG that generates this language.

^{n}b^{2m}c^{2m}d^{n}Solution