Regular Languages and Finite Automata: Lecture Notes On
Regular Languages and Finite Automata: Lecture Notes On
Lecture Notes on
Regular Languages
and Finite Automata
c A. M. Pitts, 1998-2003
First Edition 1998.
Revised 1999, 2000, 2001, 2002, 2003.
Contents
Learning Guide ii
1 Regular Expressions 1
1.1 Alphabets, strings, and languages . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Pattern matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Some questions about languages . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3 Regular Languages, I 21
3.1 Finite automata from regular expressions . . . . . . . . . . . . . . . . . . . . 21
3.2 Decidability of matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4 Regular Languages, II 29
4.1 Regular expressions from finite automata . . . . . . . . . . . . . . . . . . . 29
4.2 An example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.3 Complement and intersection of regular languages . . . . . . . . . . . . . . . 32
4.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6 Grammars 45
6.1 Context-free grammars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
6.2 Backus-Naur Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
6.3 Regular grammars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
6.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
ii
Learning Guide
The notes are designed to accompany six lectures on regular languages and finite automata
for Part IA of the Cambridge University Computer Science Tripos. The aim of this short
course will be to introduce the mathematical formalisms of finite state machines, regular
expressions and grammars, and to explain their applications to computer languages. As such,
it covers some basic theoretical material which Every Computer Scientist Should Know.
Direct applications of the course material occur in the various CST courses on compilers.
Further and related developments will be found in the CST Part IB courses Computation
Theory and Semantics of Programming Languages and the CST Part II course Topics in
Concurrency.
This course contains the kind of material that is best learned through practice. The books
mentioned below contain a large number of problems of varying degrees of difficulty, and
some contain solutions to selected problems. A few exercises are given at the end of each
section of these notes and relevant past Tripos questions are indicated there. At the end
of the course students should be able to explain how to convert between the three ways of
representing regular sets of strings introduced in the course; and be able to carry out such
conversions by hand for simple cases. They should also be able to prove whether or not a
given set of strings is regular.
Recommended books Textbooks which cover the material in this course also tend to
cover the material you will meet in the CST Part IB courses on Computation Theory and
Complexity Theory, and the theory underlying parsing in various courses on compilers.
There is a large number of such books. Three recommended ones are listed below.
D. C. Kozen, Automata and Computability (Springer-Verlag, New York, 1997).
T. A. Sudkamp, Languages and Machines (Addison-Wesley Publishing Company,
Inc., 1988).
J. E. Hopcroft, R. Motwani and J. D. Ullman, Introduction to Automata Theory,
Languages, and Computation, Second Edition (Addison-Wesley, 2001).
Note The material in these notes has been drawn from several different sources, including
the books mentioned above and previous versions of this course by the author and by others.
Any errors are of course all the author’s own work. A list of corrections will be available
from the course web page (follow links from [Link]/Teaching/). A lecture(r)
appraisal form is included at the end of the notes. Please take time to fill it in and return it.
Alternatively, fill out an electronic version of the form via the URL [Link]/cgi-
bin/lr/login.
Andrew Pitts
[Link]@[Link]
1
1 Regular Expressions
Doubtless you have used pattern matching in the command-line shells of various operating
systems (Slide 1) and in the search facilities of text editors. Another important example of
the same kind is the ‘lexical analysis’ phase in a compiler during which the text of a program
is divided up into the allowed tokens of the programming language. The algorithms which
implement such pattern-matching operations make use of the notion of a finite automaton
(which is Greeklish for finite state machine). This course reveals (some of!) the beautiful
theory of finite automata (yes, that is the plural of ‘automaton’) and their use for recognising
when a particular string matches a particular pattern.
Pattern matching
Slide 1
The purpose of Section 1 is to introduce a particular language for patterns, called regular
expressions, and to formulate some important problems to do with pattern-matching which
will be solved in the subsequent sections. But first, here is some notation and terminology to
do with character strings that we will be using throughout the course.
2 1 REGULAR EXPRESSIONS
Alphabets
(+*-,.0/1.32.54.0H0H0HZ?
Non-example:
Y
— set of all non-negative whole numbers is not
an alphabet, because it is infinite.
Slide 2
N.B. there is a unique string of length zero over $ , called the null
string (or empty string) and denoted j (no matter which $ we
are talking about).
Slide 3
1.1 Alphabets, strings, and languages 3
Concatenation of strings
Slide 4
Slides 2 and 3 define the notions of an alphabet , and the set of finite strings over an
alphabet. The length of a string t will be denoted by a~
t . Slide 4 defines the operation
of concatenation of strings. We make no notational distinction between a symbol w and
the corresponding string of length one over : so can be regarded as a subset of c . Note
that is never empty—it always contains the null string, , the unique string of length zero.
Note also that for any tJ¡7z¡7}P
(iii) If «u¬ (the empty set — the unique set with no elements), then ¤®u¯¨0 © , the set just
containing the null string.
4 1 REGULAR EXPRESSIONS
Slide 5
´ ³ Æ Ç È ²
Then, concretely speaking, the regular expressions over ° form a certain set of strings over
the alphabet obtained by adding these six symbols to ° . However it makes things more
readable if we adopt a slightly more abstract syntax, dropping as many brackets as possible
and using the convention that
So, for example, ±ÈËÊVÌ5² means ƱÈËÊ"ÆÌZÇ5²aÇ , not ƱÈËÊ-ÇVÆÌZÇ5² , or Æ>ƱÈÍÊ0ÌZÇ>Ç5² , etc.
1.2 Pattern matching 5
Slide 6
The case ãîçxæ just means that à®çï (so ï always matches áâ ); and the case ãîçñð just means
that à matches á (so any string matching á also matches áâ ). For example, if òeçôó-õö5÷Gö5ø@ù
and áçxõ÷ , then the strings matching á â are
Note that we didn’t include a regular expression for the ‘ ú ’ occurring in the UNIX
examples on Slide 1. However, once we know which alphabet we are referring to, òûç
ó-õé`ö5õêGö0ë0ë0ë3ö5õìù say, we can get the effect of ú using the regular expression
ü
õé~ýÍõê"ý5ë0ë0ë@ýÍõì8þ â
which is indeed matched by any string in ò â (because õé~ýÍõê"ý5ë0ë0ë@ýÍõì is matched by any symbol
in ò ).
6 1 REGULAR EXPRESSIONS
Slide 7
Languages
Slide 8
Some questions
Slide 9
8 1 REGULAR EXPRESSIONS
The answer to question (a) on Slide 9 is ‘yes’. Algorithms for deciding such pattern-
matching questions make use of finite automata. We will see this during the next few sections.
If you have used the UNIX utility d
egfih
, or a text editor with good facilities for regular
expression based search, like fkjml<n
o
, you will know that the answer to question (b) on Slide 9
is also ‘yes’—the regular expressions defined on Slide 5 leave out some forms of pattern
that one sees in such applications. However, the answer to the question is also ‘no’, in the
sense that (for a fixed alphabet) these extra forms of regular expression are definable, up
to equivalence, from the basic forms given on Slide 5. For example, if the symbols of the
alphabet are ordered in some standard way, it is common to provide a form of pattern for
naming ranges of symbols—for example pqlsrutv
might denote a pattern matching any lower-
case letter. It is not hard to see how to define a regular expression (albeit a rather long one)
which achieves the same effect. However, some other commonly occurring kinds of pattern
are much harder to describe using the rather minimalist syntax of Slide 5. The principal
example is complementation, : wyx=zi{
| matches w}x=zE{ iff | does not match z .
It will be a corollary of the work we do on finite automata (and a good measure of its power)
that every pattern making use of the complementation operation can be replaced by w}xWr~{
an equivalent regular expression just making use of the operations on Slide 5. But why do
we stick to the minimalist syntax of regular expressions on that slide? The answer is that it
reduces the amount of work we will have to do to show that, in principle, matching strings
against patterns can be decided via the use of finite automata.
The answer to question (c) on Slide 9 is ‘yes’ and once again this will be a corollary of
the work we do on finite automata. (See Section 5.3.)
Finally, the answer to question (d) is easily seen to be ‘no’, provided the alphabet
contains at least one symbol. For in that case
is countably infinite; and hence the number of
languages over , i.e. the number of subsets of
is uncountable. (Recall Cantor’s diagonal
argument.) But since is a finite set, there are only countably many regular expressions
over . (Why?) So the answer to (d) is ‘no’ for cardinality reasons. However, even amongst
the countably many languages that are ‘finitely describable’ (an intuitive notion that we will
not formulate precisely) many are not of the form x=zi{
for any regular expression . For z
example, in Section 5.2 we will use the ‘Pumping Lemma’ to see that
U
UDg
is not of this form.
1.4 Exercises
Exercise 1.4.1. Write down an ML data type declaration for a type constructor legf8d8
8h
whose values correspond to the regular expressions over an alphabet . l
Exercise 1.4.2. Find regular expressions over
U<i that determine the following languages:
(a)
| | contains an even number of ’s
1.4 Exercises 9
Exercise 1.4.4. If an alphabet contains only one symbol, what does
look like? (Answer:
see Example 1.1.1(i).) So if D 8
is the set consisting of just the null string, what is ?
(The answer is not 8
.) Moral: the punctuation-free notation we use for the concatenation of
two strings can sometimes be confused with the punctuation-free notation we use to denote
strings of individual symbols.
£ ¢
¡ ¢
¤ ¢ i ¥ ¢ ¦
£ £ £
¡
¤ i¥ ¦
States: , , , .
Input symbols: § , ¨ .
¡
Transitions: as indicated above.
Start state: .
Accepting state(s): .
¦
Slide 10
The key features of this abstract notion of ‘machine’ are listed below and are illustrated
by the example on Slide 10.
© There are only finitely many different states that a finite automaton can be in. In the
ªU« ªi¬ ªk
example there are four states, labelled , , , and . ª®
© We do not care at all about the internal structure of machine states. All we care about
is which transitions the machine can make between the states. A symbol from some
¯
fixed alphabet is associated with each transition: we think of the elements of ¯
as input symbols. Thus all the possible transitions of the finite automaton can be
specified by giving a finite graph whose vertices are the states and whose edges have
12 2 FINITE STATE MACHINES
°
both a direction and a label (drawn from ). In the example °²±K³U´µ·¶U¸ and the only
possible transitions from state are ¹8º
¹iº½¼ » ¹¾ and ¹iº¼½ ¿ ¹kÀÁ
In other words, in state ¹Eºthe machine can either input the symbol and enter state ¶
¹Â¾ ´ ¹À
¹Uà ¼½ ¿ ¹Ã
, or it can input the symbol and enter state . (Note that transitions from a state
back to the same state are allowed: e.g. in the example.)
Ä The states are partitioned into two kinds: accepting states2 and non-accepting states.
In the graphical representation of a finite automaton, the accepting states are indicated
by double circles round the name of each such state, and the non-accepting states are
indicated using single circles. In the example there is only one accepting state, ; the ¹Ã
other three states are non-accepting. (The two extreme possibilities that all states are
accepting, or that no states are accepting, are allowed; it is also allowed for the start
state to be accepting.)
The reason for the partitioning of the states of a finite automaton into ‘accepting’ and
‘non-accepting’ has to do with the use to which one puts finite automata—namely to recognise
whether or not a string ÅÇÆÈ°É
is in a particular language ( subset of ±
). Given we °É Å
begin in the start state of the automaton and traverse its graph of transitions, using up the
Å
symbols in in the correct order reading the string from left to right. If we can use up all the
Å Å
symbols in in this way and reach an accepting state, then is in the language ‘accepted’
Å
(or ‘recognised’) by this particular automaton; otherwise is not in that language. This is
summed up on Slide 11.
1
The term initial state is a common synonym for ‘start state’.
2
The term final state is a common synonym for ‘accepting state’.
2.1 Finite automata 13
Slide 11
ýÿþ=ö é
contains three consecutive ’s ú
(For ( ì é ëó
) corresponds to the state in the process of reading a string in which the
last symbols read were all ’s.) So ú ÿý þ=ö
coincides with the language determined by ýþ
the regular expression
séKþ ú
û ñ ú
úgú þ=ú
û ñ
(cf. Slide 8).
14 2 FINITE STATE MACHINES
Slide 12
GVO2W4XZYMX\[] D SO_^ D
The reason for the qualification ‘non-deterministic’ on Slide 12 is because in general,
for each state and each input symbol , we allow the possibilities that
C`DP GaRTSU
there are no, one, or many states that can be reached in a single transition labelled from , S G
corresponding to the cases that has no, one, or many elements. For example, if F
is the NFA pictured on Slide 13, then
CEDQP GbRTcUedgf i.e. in F , no state can be reached from Gb with a transition labelled c ;
CEDQP GbRTS$UedhGiNj i.e. in F , precisely one state can be reached from Gkb with a transition
labelled S ;
CEDQP GlRTS$UedhGlRmGbj i.e. in F , precisely two states can be reached from Gl with a
transition labelled S .
2.2 Determinism, non-determinism, and -transitions n 15
ok{}|2okpAqrsa~Ea{ p s
contains three consecutive ’s
Slide 13
The finite automaton pictured on Slide 10 is deterministic. But note that if we took the
same graph of transitions but insisted that the alphabet of input symbols was TNT
say,
then we have specified an NFA not a DFA, since for example
TI
. The moral of
this is: when specifying an NFA, as well as giving the graph of state transitions, it is important
to say what is the alphabet of input symbols (because some input symbols may not appear in
the graph at all).
When constructing machines for matching strings with regular expressions (as we will
do in Section 3) it is useful to consider finite state machines exhibiting an ‘internal’ form
of non-determinism in which the machine is allowed to change state without consuming any
n
input symbol. One calls such transitions -transitions and writes them as
2 N
This leads to the definition on Slide 15. Note that in an NFA ,
is not an element of the alphabet
of input symbols.
, we always assume that n
16 2 FINITE STATE MACHINES
¦ /§¨¥ , the
is an NFA with the property that 6
¦ ® for each ,- !¡#¢$¡&£¤k¥ and
finite set ©¥2ª«¬
element—call it ¯¥/ª«¬
°
¦ ® .
contains exactly one
Slide 14
¸
An NFA with -transitions (NFA ) ¹
is specified by an NFA together with a binary relation, called
¸
the -transition relation, on the set A¡&¢$¡&£¤ ¥ . We write
´³ ¹ µ
®
to indicate that the pair of states ª«¬º µ is in this relation.
¦
Example (with input alphabet = » ¬¼½ ):
Slide 15
2.3 A subset construction 17
Slide 16
ó ý þ«ÿMþ
construction. The name ‘subset construction’ refers to the fact that there is one state of ûÑè
ó ýûÑþ«ÿMè þ óè
for each subset
is a transition
of the set
in
of states of
just in case
. Given two subsets
è ðó
, there
consists of all the -states reachable from
18 2 FINITE STATE MACHINES
states in via the relation defined on Slide 16, i.e. such that we can get from to
in via finitely many -transitions followed by an -transition followed by finitely many
-transitions.
)$*,+ - .
" / / /
Slide 17
By definition, the start state of 78 is the subset of 9;:<$:=>? whose elements are the
states reachable by -transitions from the start state of ; and a subset A@B9;:<$:=>$? is an
accepting state of 7C iff some accepting state of is an element of . Thus in the example
on Slide 17 the start state is DEEF'GH'IJGH
KL and
Indeed, in this case PSR_]Ua`bPSRcedMEdJUa`bPSRT78]U . The fact that and 7C accept the same
language in this case is no accident, as the Theorem on Slide 18 shows. That slide also gives
the definition of the subset construction in general.
2.3 A subset construction 19
s ~,
in ijg iff
wpq
l|
n , where
~, E| ¡
l|
n p u
l
5 in gon
s¢ ~£¤E| ¢ ¡
p 5¥ f
Slide 18
To prove the theorem on Slide 18, given any NFA¯±° we have to show that ²S³_°]´¶µ
²S³_·C°]´ . We split the proof into two halves.
¾ ¿
Proof that ²O³T°]´¸²S³_·C°]´ . Consider the case of ¹ first: if ¹»º²S³_°]´ , then ¼'½ ¯ for
¿
some ºÀSÁÂÁÂÃÅÄ«Æ ½ , hence ¼ÇȽ¤ºÀSÁÂÁÂÃÅÄÆ Çw½ and thus ¹º²S³T·8°]´ . Now given any non-
null string ÉʵÌËÎÍHËzÏÐ
Ð
ÐyË!Ñ , if É is accepted by ° then there is a sequence of transitions in
° of the form
¾ ¿ ¾ Õ
Õ
Õ ¾¿
(1) ¼½Ò
Ó Í±Ò4Ô Ò4Ö Ñ׺ØÀOÁÁÂÃÅÄ«Æ ½ Ð
Since it is deterministic, feeding Ë«ÍHËzÏÙÐ
Ð
Ð|Ë!Ñ to ·8° results in the sequence of transitions
ÚÒ
Û Ó Ü Í
Ú4 Õ
Õ
Õ ÝÚ ÚÞÛ
(2) ¼EÇȽ ÒÛÔ Ò Ö
J Ü Ñ
where Ü ÍßµªàJÇw½®³á¼EÇȽ»âÂËÎÍy´ , Ü ÏOµªàJÇȽʳ Ü Í
âÂËÏJ´ , etc. By definition of à
Çw½ (Slide 18), from
(1) we deduce
¿ Ü Í
Í㺻àJÇw½Ø³á¼EÇw½¥âÂËÎÍy´£µ
¿
so ϶º»àJÇw½Ø³ Ü Í
âÂËzÏJ´aµ Ü Ï
Ð
Ð
Ð
¿
so Ѻ»àJÇw½Ø³ Ü ÑzäwÍEâÂË!Ñ´,µ Ü Ñ
20 2 FINITE STATE MACHINES
and hence å
æçÊèSéÂéÂêÅëìíwî (because ïJæçÊèSéÂéÂêë«ìî ). Therefore (2) shows that ð is accepted
by ñ8ò .
Proof that óOôTñCòVõöóOôTò]õ . Consider the case of ÷ first: if ÷Aç óOôTñCòVõ , then ø íÈî ç
û
èSéÂéÂêÅëì íwî and so there is some ïçø íÈî with ïZçùèSéÂéÂêÅë«ì î , i.e. ø î ú ï\çüèSéÂéêÅë«ì î
and thus ÷çbóOôTò]õ . Now given any non-null string ðuýÿþÂþþ!æ , if ð is accepted by
ñCò then there is a sequence of transitions in ñCò of the form (2) with å æçbèSéÂéÂêÅëì íwî ,
i.e. with å
æ containing some ï
æBç èSéÂéêÅë«ìî . Now since ï
æBç åæùý íwî ôáåæ
Âþ!æõ ,
û
by definition of íÈî there is some ï
æç åæ with ïJæ
ïJæ in ò . Then since
û
ïJæ ®çBåæ ý íwî ôcå
æ
Âþ5æHõ , there is some ïJæ\çBåæ with ïJæ
ïJæ .
Working backwards in this way we can build up a sequence of transitions like (1) until, at the
û
last step, from the fact that ï±çåãý íwî ôcø íwî
ÂþÂõ we deduce that ø î
ï . So we get
a sequence of transitions (1) with ïEæ×çÊèSéÂéÂêë«ì î , and hence ð is accepted by ò .
2.4 Summary
The important concepts in Section 2 are those of a deterministic finite automaton (DFA) and
the language of strings that it accepts. Note that if we know that a language ó is of the form
ó ýAóSôTòVõ for some DFA ò , then we have a method for deciding whether or not any given
string ð (over the alphabet of ó ) is in ó or not: begin in the start state of ò and carry out
the sequence of transitions given by reading ð from left to right (at each step the next state is
uniquely determined because ò is deterministic); if the final state reached is accepting, then
ð is in ó , otherwise it is not.
We also introduced other kinds of finite automata (with non-determinism and ÷ -
transitions) and proved that they determine exactly the same class of languages as DFAs.
2.5 Exercises
Exercise 2.5.1. For each of the two languages mentioned in Exercise 1.4.2 find a DFA that
accepts exactly that set of strings.
Exercise 2.5.2. The example of the subset construction given on Slide 17 constructs a DFA
with eight states whose language of accepted strings happens to be óSôcþ4õ . Give a DFA
with the same language of accepted strings, but fewer states. Give an NFA with even fewer
states that does the same job.
Exercise 2.5.3. Given a DFA ò , construct a new DFA ò! with the same alphabet of input
symbol " î and with the property that for all ðùç#"$î , ð is accepted by ò% iff ð is not
accepted by ò .
Exercise 2.5.4. Given two DFAs ò&
Hò' with the same alphabet " of input symbols,
construct a third such DFA ò with the property that ðqç(" is accepted by ò iff it is
accepted by both ò& and ò) . [Hint: take the states of ò to be ordered pairs ôTï
Hï
õ of
states with ï ç+*;ì-,$ìê. î and ïSç/*Îì0,$ìê1. î$2 .]
Tripos questions 2001.2.1(d) 2000.2.1(b) 1998.2.1(s) 1995.2.19 1992.4.9(a)
21
3 Regular Languages, I
Slide 19 defines the notion of a regular language, which is a set of strings of the form 35476!8
for some DFA 6 (cf. Slides 11 and 14). The slide also gives the statement of Kleene’s
Theorem, which connects regular languages with the notion of matching strings to regular
expressions introduced in Section 1: the collection of regular languages coincides with the
collection of languages determined by matching strings with regular expressions. The aim of
this section is to prove part (a) of Kleene’s Theorem. We will tackle part (b) in Section 4.
Definition
A language is regular iff it is the set of strings accepted by some
deterministic finite automaton.
Kleene’s Theorem
(a) For any regular expression 9 , :<;=9?> is a regular language
(cf. Slide 8).
Slide 19
(i) For each atomic form of regular expression, X ( X'Y&Z ), [ , and \ , we give an NFA]
accepting just the strings matching that regular expression.
(ii) Given any NFA] s ^`_ and ^'a , we construct a new NFA] , bcedgfch7^`_ij^'ak with the
property
l l l
hbcedgfch7^`_ij^)amknkNoqpr+srEY h7^`_tk or rEY h7^)amk1uv
l l l l l l
Thus h7wV_s wxakJo hbcedgfch7^`_ij^'amknk when 7h wV_tkNo hU^y_tk and hUwamkJo h7^'ak .
(iii) Given any NFA] s ^`_ and ^'a , we construct a new NFA] , z{fc|j}~h7^`_ij^)ak with the
property
l l l
hzfc|j}~1h7^`_ij^)aknkNo#pr_nra@sxr_Y h7^`_tk and ra$Y h7^'ak1uv
l l l l l l
Thus h7wV_nwxakNo hzfc|j}~mhU^y_ij^'aknk when Uh w_tkJo hU^y_tk and h7wxako h7^'ak .
(iv) Given any NFA] ^ , we construct a new NFA] , ~0}h7^!k with the property
l l
h=
~0}h7^#knkoqpr_jravvvrFs and each r
NY h7^!ktuv
l l l l
Thus h7wmkJo h~-}hU^!knk when Uh wVkNo h7^#k .
Thus starting with step (i) and applying the constructions in steps (ii)–(iv) over and over
again, we eventually build NFA] s with the required property for every regular expression w .
Put more formally, one can prove the statement
for all +y , and for all regular expressions of size , there exists an NFA]
l l
^ such that h7wVkNo h7^!k
by mathematical induction on , using step (i) for the base case and steps (ii)–(iv) for the
induction steps. Here we can take the size of a regular expression to be the number of
occurrences of union ( s ), concatenation ( / ), or star ( Q ) in it.
l
Step (i) Slide 20 gives NFAs whose languages of accepted strings are respectively
l l h7X?ko
pxXu (any XYFZ ), h[kNo%p[u , and h\kNo\ .
3.1 Finite automata from regular expressions 23
accepts no strings
Slide 20
Step (ii) Given NFA s ` and )¡ , the construction of ¢£e¤g¥£¦7y §j)¡¨ is pictured on
Slide 21. First, renaming states if necessary, we assume that ©ª-«ª=¬1®Q¯ and ©ª-«ª=¬1®$° are
disjoint. Then the states of ¢£e¤g¥£¦7y §j)¡m¨ are all the states in either y or )¡ , together
with a new state, called ±² say. The start state of ¢ £¤g¥£¦U& §j'¡¨ is this ±² and its accepting
states are all the states that are accepting in either or )¡ . Finally, the transitions of
¢£e¤g¥£¦7` §j'¡¨ are given by all those in either & or )¡ , together with two new ³ -
transitions out of ±² to the start states of y and '¡ .
¼
Thus if ´¶µ¸·5¦7y t¨ , i.e. if we have ¹®Q¯»º ± for some ± ½µ¿¾$ÀtÀt¬0Áª ®Q¯ , then we
à ¼
get ±²  ¹x®Q¯ º ± showing that ´ µÄ·5¦¢£e¤g¥£¦7y §j'¡¨ . Similarly for )¡ . So
·5¦¢£e¤g¥£¦7` §j'¡m¨n¨ contains the union of ·5¦7& t¨ and ·$¦7'¡¨ . Conversely if ´ is accepted by
¢£e¤0¥£¦7y m§j)¡¨ , there is a transition sequence ±² ¼ º ± with ±ÅµM¾$ÀtÀt¬-Áª ®Q¯ or ±ÅµM¾5À1Àt¬0Áª ®$° .
Clearly, in either case this transition sequence has to begin with one or other of the ³ -
transitions from ±² , and thereafter we get a transition sequence entirely in one or other of
` or )¡ finishing in an acceptable state for that one. So if ´MµM·5¦¢£e¤g¥£ ¦7 §j'¡m¨n¨ , then
either ´ÆµE·5¦7y j¨ or ´EµÆ·5¦7)¡m¨ . So we do indeed have
ÍÎÐÏ-ÑÎÓÒ=Ô%ÕVÖmÔØ×VÙ
ÚÛÜ Ô Õ
ß
ÝÞ
ß Ú ÛÅà Ô ×
Slide 21
Step (iii) Given NFAæ s çyè and ç)é , the construction of êëìíjîïmð7ç&èmñjç)éò is pictured on
Slide 22. First, renaming states if necessary, we assume that óï-îï=ô1õöQ÷ and óï-îï=ô1õö$ø are
disjoint. Then the states of êëìíjîïmðUç&èñjç'éò are all the states in either çyè or ç'é . The start
state of êëìíjîïðUçyèñjç'émò is the start state of çyè . The accepting states of êëìíjîïð7çyèñjç)éò
are the accepting states of çé . Finally, the transitions of êëìíjîïð7çyèñjç)éò are given by all
those in either ç&è or ç)é , together with new ù -transitions from each accepting state of çúè to
the start state of ç)é (only one such new transition is shown in the picture).
Thus if û èQüMý$ð7ç`ètò and ûé@üý5ð7ç'éò , there are transition sequences þöQ÷@ÿ
÷
è in ç`è
with è ü 5í1ítô ï öQ÷ , and þö$ø ÿ
ø
é in ç'é with éHü 5í1ítô ï ö$ø . These combine to yield
þxöQ÷$
ÿ è æ þö$øH
÷ ø
ÿ é
in êëìítîïð7çyèmñjç)éò witnessing the fact that û èjûé is accepted by ê{ëìíjîïmð7çyèñjç'éò . Con-
versely, it is not hard to see that every )üý5ðêëìíjîïð7çèmñjç)éònò is of this form. For any
transition sequence witnessing the fact that is accepted starts out in the states of çØè but
finishes in the disjoint set of states of çé . At some point in the sequence one of the new
ù -transitions occurs to get from ç&è to ç'é and thus we can split as
ûèjûé with û è
accepted by çyè and ûé accepted by ç)é . So we do indeed have
ý$ðêëìíjîïð7ç`èñjç'éònò
û èjûéû èüÆý$ð7ç`ètò and ûé üÆý$ðUç)éò
3.1 Finite automata from regular expressions 25
!#"%$'&("*),+
Slide 22
Clearly, <>=@?2ACBJ:GE L
accepts (since its start state is accepting) and any concatenation of
:
one or more strings accepted by . Conversely, if is accepted by N
, the occurrences <>=@?2ACBD:FE
HKI
of in a transition sequence witnessing this fact allow us to split into the concatenation of N
zero or more strings, each of which is accepted by . So we do indeed have :
O BP<>=@?2ABD:GE8EQRTSVUWSYXZKZKZPS\[^]T_`ba and each S\ced O BD:FEgfZ
26 3 REGULAR LANGUAGES, I
hji8klnmPoqp
r2s t u2v o
t
The only accepting state of
j
h 8
i
k n
l P
m q
o p is r s .
Slide 23
This completes the proof of part (a) of Kleene’s Theorem (Slide 19). Figure 1 shows how
the step-by-step construction applies in the case of the regular expression wyx{z}|(~gx
to produce
an NFA
satisfying wJG~
wwyxVz |~gxC~
. Of course an automaton with fewer states and
-transitions doing the same job can be crafted by hand. The point of the construction is that
it provides an automatic way of producing automata for any given regular expression.
Note. The subset construction used to convert the NFA resulting from steps (i)–(iv) of
Section 3.1 to a DFA produces an exponential blow-up of the number of states. ( has
3.2 Decidability of matching 27
2 states if ¡ ¢
has .) This makes the method described above very inefficient. (Much more
efficient algorithms exist.)
3.3 Exercises
Exercise 3.3.1. Why can’t the automaton £>¤@¥2¦C§D¡F¨
required in step (iv) of Section 3.1 be
¡
constructed simply by taking , making its start state the only accepting state and adding
©
new -transitions back from each old accepting state to its start state?
Exercise 3.3.3. Show that any finite set of strings is a regular language.
4 Regular Languages, II
The aim of this section is to prove part (b) of Kleene’s Theorem (Slide 19).
ðòñ ë íKì î}í ïóõô÷öÆø é ñ8ù å óWúüû æþÿ ý ú æÆè in Ú with all inter-
mediate states of the sequence
Û .
in
ðòñ Ú ó ô ðòñ ë ó , where ë ô ë ûû ë and
ô number of accepting states,
Hence
Slide 24
Proof of the Lemma on Slide 24. The regular expression ³Æ¹¸ º}¹» can be constructed by induc-
tion on the number of elements in the subset . ¼
1
The lemma works just as well whether
is deterministic or non-deterministic; it also works for
NFA s, provided we replace by (cf. Slide 16).
30 4 REGULAR LANGUAGES, II
Base case, is empty. In this case, for each pair of states , we are looking for a regular
expression to describe the set of strings
"!$# &' (*% ) with no intermediate states +,
So each element of this set is either a single input symbol - (if ' ( . holds in / ) or
possibly 0 , in case *12 . If there are no input symbols that take us from to in / , we
can simply take ACB
3 574 685:9<;>1 =@? if E1F
D
0 if G1F .
On the other hand, if there are some such input symbols, -IH,,,J:-LK say, we can take
A #:OOO"#
3 574 685 9 ;M1 =@? -NH #:OOO"# -K # if E1F D
-NH -K 0 if G1F .
Induction step. Suppose we have defined the required regular expressions for all subsets
P PRQTS UWVX
ZY "U+*1 V[ # \1
of states with elements. If is a subset with elements, choose some element
and consider the -element set P . Then for any pair of states D 7U+
L V$]_^a`^cbJd"e
, by inductive hypothesis we have already constructed the regular expressions
3 H ;>1 =@? 3 57fh685:gM9i 5ajk m3 l >; 1 =@? 3 57fn685cgMj i 5aj:k 3"o >; 1 =@? 3 5afnj>gM685ai j 5cjk and 3 p >; 1 =@? 3 a5fnj>gM685:i 9 5cjk ,
Note also that at the inductive steps in the construction of a regular expression for |
}m~
we are free to choose which state to remove from the current state set . A good rule of
thumb is: choose a state that disconnects the automaton as much as possible.
Example
Direct inspection yields:
r
N m
Slide 25
As an example, consider the NFA shown on Slide 25. Since the start state is and this
~7 ~78~ 8J
is also the only accepting state, the language of accepted strings is that determined by the
regular expression . Choosing to remove state from the state set, we have ¡
(3) ¢¤£z¥~7 ~7 ~ J ¦¨§ ¢¤£z¥~7 ~78~ J © ¥~7 ~7 J £r ~7ª«J ¦:¬ ¥ ~78~ J ¦M
Direct inspection shows that ¢y£r~7 8~ ¦X§ ¢¤£® ¬ ¦ and ¢y£r¥~7 ¦¯§ y
~78J ~7J ¢ £® M¬ ° ¦ . To calculate
¢¤£z¥ ~7 J ¦ , and ¢y£r¥ ~7 ~ J ¦ , we choose to remove state ± :
¢¤£z¥ ~7 J ¦¨§ ¢¤£z¥ ~M © ~M £z¥> ~M ¦:¬ ¥> ~M ¦
¢¤£z¥ ~78~ J ¦¨§ ¢¤£z¥ ~M8~ © ~M £z¥> ~M ¦:¬ ¥> ~M8~ ¦M
These regular expressions can all be determined by inspection, as shown on Slide 25. Thus
which is equal to µy¶·L··_¸M¹ . Substituting all these values into (3), we get
µ¤¶zº¥¼7»¼7½8¼ ½¾½¿JÀ ¹¨ÁFµy¶· ¸Â · ¸Mà ¶³Ä  ·L· ¸Mà ¹ ¸ ··L· ¸ ¹JÅ
So · ¸ Â · ¸ Ã ¶zÄ Â ·L· ¸ Ã ¹ ¸ ·L·· ¸
is a regular expression whose matching strings comprise the
language accepted by the NFA on Slide 25. (Clearly, one could simplify this to a smaller, but
equivalent regular expression (in the sense of Slide 8), but we do not bother to do so.)
Complementation Recall that on page 8 we mentioned that for each regular expression º
Æ
over an alphabet , we can find a regular expression ÇȶrºÉ¹
that determines the complement
of the language determined by : º
µy¶@ÇȶrºÉ¹¹ÊÁÌË"ÍÎXÆ ¸Ï Í[ÎÑÐ µ¤¶rº ¹JÒÅ
As we now show, this is a consequence of Kleene’s Theorem.
ÕÓ ÔLÖ×cØÚÙ
Û&Ü ÖÝLÖÞmßàâáJãåäçæXèâé"ì êë Ü ÖÝLÖÞmß æ
Ûîí àâáJãåäçæXèâé"ì êë í æ
Û transitions of ÓÕÔLÖm×åØïÙ = transitions of Ø
Û start state of ÓÕÔLÖ"×åØïÙ = start state of Ø
Ûîðòñ7ñ ÞónÖ àôáMãcäõæXè ì÷ö¥øEù Ü ÖÝLÖÞmß æ ú ø[ù û ðòñ>ñ ÞónÖ æ[ü .
Ø is a deterministic finite automaton, then ý is
Provided
accepted by
ÓÕÔLÖ"×åØïÙ iff it is not accepted by Ø :
þ×ÓÕÔLÖ×cØÚÙJÙ ì÷ö ý ù íWÿ ú ý ù û þÏ×cØÚÙ ü .
Slide 26
4.3 Complement and intersection of regular languages 33
Lemma 4.3.1. If is a regular language over alphabet , then its complement
is also regular.
Proof. Since is regular, by definition there is a DFA such that
. Let
be the DFA constructed from as indicated on Slide 26. Then
!
" is the set
of strings accepted by #$ and hence is regular.
Given a regular expression % , by part (a) of Kleene’s Theorem there is a DFA such
that &$%'()$* . Then by part (b) of the theorem applied to the DFA , we can
find a regular expression +,$%- so that .+/$%-012345$*0 . Since
2345$*067
897:
;<
&$%'=?>
Note. The construction given on Slide 26 can be applied to a finite automaton whether or
not it is deterministic. However, for &2#0 to equal <(
@A
8 we need
to be deterministic. See Exercise 4.4.2.
Intersection As another example of the power of Kleene’s Theorem, given regular expres-
sions %'B and %;C we can show the existence of a regular expression $%DB=E(%;CF with the property:
Lemma 4.3.2. If &B and HC are a regular languages over an alphabet , then their
intersection
N.O :
;:9B and :HC
9BJIKHCML#P
is also regular.
Proof. Since &B and QC are regular languages, there are DFA RB and !C such that
TS1U
SV (WXZY'>8[ ). Let \9]_^`$aB>G!C# be the DFA constructed from B and C as on
Slide 27. It is not hard to see that \9]_^b$B>G!C has the property that any : is accepted
by \9]_^b$cB#>GC iff it is accepted by both B and C . Thus 9B_I,HC2\9]_^d$cB#>GC50
is a regular language.
34 4 REGULAR LANGUAGES, II
ef1g1hjilk-mion'p
q erfsg6hti*k-mion'p h2u@k-m5u-n?p
states of are all ordered pairs with
u kvawJx0y@x{z;|-}~ u n/vcwJx{yx{z;|-}r
and
q erfsgshji*k-mion?p ik
alphabet of is the common alphabet of
i n
and
q htuk'm#u4n'p h2uk m#un p erfsg6hti*k4mion'p uDk uk ilk
in iff
in
u-n u?n iAn
and
in
q efsg6hti k m#i n p h{ }~ mF }r p
start state of is
q htuk'm#u4n'p erfsgshji*k-mion?p uDk i*k
accepting in iff accepting in
u-n iAn
and accepting in .
Slide 27
Thus given regular expressions and ; , by part (a) of Kleene’s Theorem we can find
DFA c and ! with $FVZ&$
V ('8 ). Then by part (b) of the theorem we can
find a regular expression ?G(; so that &$?0 ;F&29bb$aG!0 . Thus matches
'=(; iff 9_`$aG! accepts , iff both and ! accept , iff matches both ? and
; , as required.
4.4 Exercises
Exercise 4.4.1. Use the construction in Section 4.1 to find a regular expression for the DFA
whose state set is ;F'8D , whose start state is , whose only accepting state is , whose
alphabet of input symbols is ;¡¢=£; , and whose next-state function is given by the following
table. ¤¥§¦
¡ £
Exercise 4.4.2. The construction ¨© ª«¬$* given on Slide 26 applies to both DFA and
NFA; but for 2ª3«4¬5$*0 to be the complement of $* we need to be deterministic.
Give an example of an alphabet and a NFA with set of input symbols , such that
± &$= is not the same set as &2ª«¬#0 .
:®9¯3°
®
4.4 Exercises 35
Exercise 4.4.3. Let ²´³ µV¶¸· ¹º8»5¶@¹4µV¶¸· ¹º=» . Find a complement for ² over the alphabet
¼ ¼
³Z½;¶¿¾=¹;À , i.e. a regular expressions Áµ$²'º over the alphabet satisfying Â&µ.Áµ²'º0ºH³Z½ÃÅÄ
¼
Æ Âµ²'º8À . Do the same for the alphabet ½;¶¢¾=¹¾=ÇÀ .
» ·;Ã
Ä:
In the context of programming languages, a typical example of a regular language (Slide 19)
is the set of all strings of characters which are well-formed tokens (basic keywords, identifiers,
etc) in a particular programming language, Java say. By contrast, the set of all strings which
represent well-formed Java programs is a typical example of a language that is not regular.
Slide 28 gives some simpler examples of non-regular languages. For example, there is no
way to use a search based on matching a regular expression to find all the palindromes in a
piece of text (although of course there are other kinds of algorithm for doing this).
È
The set of strings over É¢Ê=ËÌË#ÍJËÎ?Ë4ÏÏ4Ï?Ë#ÐbÑ in which the
parentheses ‘ Ê ’ and ‘ Ì ’ occur well-nested.
È
The set of strings over ÉÍJËÎ?Ë4ÏÏ4Ï-Ë5ÐdÑ which are palindromes,
i.e. which read the same backwards as forwards.
È
ÉÍ¢Ò¢ÎFÒÓDÔÖÕ×_Ñ
Slide 28
The intuitive reason why the languages listed on Slide 28 are not regular is that a machine
for recognising whether or not any given string is in the language would need infinitely many
different states (whereas a characteristic feature of the machines we have been using is that
they have only finitely many states). For example, to recognise that a string is of the form Ø¿ÙÚ5Ù
one would need to remember how many Ø s had been seen before the first Ú is encountered,
requiring countably many states of the form ‘just seen Û Ø s’. This section make this intuitive
argument rigorous and describes a useful way of showing that languages such as these are
not regular.
The fact that a finite automaton does only have finitely many states means that as we look
at longer and longer strings that it accepts, we see a certain kind of repetition—the pumping
lemma property given on Slide 29.
38 5 THE PUMPING LEMMA
Slide 29
Since is regular, it is equal to the set of strings accepted by some DFA . Then we
can take the number
mentioned on Slide 29 to be the number of states in . For suppose
÷
þ ÿ with
. If , then there is a transition sequence as shown at
the top of Slide 30. Then can be split into three pieces as shown on that slide. Note that
by choice of and , "!$#%&$õ' ÷ )(+* and "!$#%&$ý þ0õ" ÷ -,.
. So it just remains
to check that ýJþGõ ý_ÿ/ for all 021 . As shown on the lower half of Slide 30, the string
the machine from state 34 back÷ to the same state (since 34 ÷ 365 ). So for any ,
õ takes
ý¸þGõ ý_ÿ takes us from the initial state 7$8 39 to 3:4 , then times round the loop from 3;4 to
itself, and then
from 34 to 3 <=>=>@?A# 8 . Therefore for any 21 , ý þGõ ýbÿ is accepted by
, i.e. ýJþGõ ýbÿ .
Note. In the above construction it is perfectly possible that ÷ 1 , in which case ý6þ is the
null-string, ø .
5.2 Using the Pumping Lemma 39
Slide 30
Remark 5.1.1. One consequence of the pumping lemma property of and is that if there
is any string in of length . , then contains arbitrarily long strings. (We just ‘pump
up’ by increasing .)
If you did Exercise 3.3.3, you will know that if is a finite set of strings then it is regular.
In this case, what is the number with the property on Slide 29? The answer is that we can
take any strictly greater than the length of any string in the finite set . Then the Pumping
Lemma property is trivially satisfied because there are no with "$&+ for
which we have to check the condition!
The Pumping Lemma (Slide 5.1) says that every regular language has a certain property—
namely that there exists a number with the pumping lemma property. So to show that
a language is not regular, it suffices to show that no possesses the pumping
lemma property for the language . Because the pumping lemma property involves quite a
complicated alternation of quantifiers, it will help to spell out explicitly what is its negation.
This is done on Slide 31. Slide 32 gives some examples.
40 5 THE PUMPING LEMMA
Slide 31
Examples
Slide 32
5.2 Using the Pumping Lemma 41
Proof of the examples on Slide 32. We use the method on Slide 31.
(i) For any ìÎíïî , consider the string ðòñïóôRõ>ô . It is in öx÷ and has length íøì . We show
that property ( ù ) holds for this ð . For suppose ð ñ ó"ôRõ>ô is split as ð ñ úÞ÷kûËúÀü with
ýþ ÿ ú÷kû
¤ì and ýþ ÿ û íòî . Then ú ÷Rû must consist entirely of ó s, so ú ÷ ñòó
and û/ñó say, and hence úÀüáñócô
6õ6ô . Then the case ñ of úÞ÷Rû"úÀü is not in öx÷ since
(iii) Given ìàí î , since there are infinitely many primes + , we can certainly find one satisfying
+-,/.ì . I claim that ðñ®ó0 has property ( ù ). For suppose ð+ñ+ó0 is split as ðñ+ú÷kûúAü
with
ýþ ÿ ' ú÷kû 1
ì and ýþ ÿ ' ûí î . Letting 243ñ 576 ýþ ÿ ' ú÷8 and #93ñ 576 ýþ ÿ ' û , so
that
ýþ ÿ ' úÀü:½ñ)+&!;21!)# , we have
úÞ÷Rû 0 úÀüáñó
ó =< 0 > ó 0
ñó 0 @?BA 0 ñó <CA
÷ >D< 0 >BE
Remark 5.2.1. Unfortunately, the method on Slide 31 can’t cope with every non-regular
language. This is because the pumping lemma property is a necessary, but not a sufficient
condition for a language to be regular. In other words there do exist languages ö for which a
number ì/íî can be found satisfying the pumping lemma property on Slide 29, but which
nonetheless, are not regular. Slide 33 gives an example of such an ö .
42 5 THE PUMPING LEMMA
[For any qsrut of length vRw , can take xzyT{J| , }4{ first letter of q ,
xk~{ rest of q .]
U
But is not regular. [See Exercise 5.4.2.]
Slide 33
If ²³¤s£ , then not all the ²OÊP¥ states in this sequence can be
distinct and we can shorten it as on Slide 30. But then we would
obtain a strictly shorter string in ¦9§¢Ë© contradicting the choice of
«¬«k®¯°¯¯:«b± . So we must have ²³Ìs£ .
Slide 34
5.4 Exercises
Exercise 5.4.1. Show that the first language mentioned on Slide 28 is not regular.
Exercise 5.4.2. Show that there is no DFA Í for which Î1ÏÍnÐ is the language on Slide 33.
[Hint: argue by contradiction. If there were such an Í , consider the DFA ÍÒÑ with the same
states as Í , with alphabet of input symbols just consisting of Ó and Ô , with transitions all
those of Í which are labelled by Ó or Ô , with start state ÕGÖ×Ï7ØGÖOÙ8ÚÐ (where Ø°Ö is the start
state of Í ), and with the same accepting states as Í . Show that the language accepted by
ÍÛÑ has to be ÜGÓÝÞÔßÝàYáHâ³ã ä and deduce that no such Í can exist.]
Exercise 5.4.3. Check the claim made on Slide 33 that the language mentioned there satisfies
the pumping lemma property of Slide 29 with åçæÛè .
6 Grammars
We have seen that regular languages can be specified in terms of finite automata that accept
or reject strings, and equivalently, in terms of patterns, or regular expressions, which strings
are to match. This section briefly introduces an alternative, ‘generative’ way of specifying
languages.
òêóð*î
þúû
Slide 35
element alphabet
ú
!" #
$ &%('
Slide 35 gives an example of a context-free grammar for generating strings over the seven
The elements of the alphabet are called terminals for reasons that will emerge below. The
grammar uses finitely many extra symbols, called non-terminals, namely the eight symbols
õ ) ! * '
ñGêíìböGòê õóìböí÷ê ëô°ïë ë ôïëøùó õ éê =ôðbñ°ê íì =éê ëìêëíê =é°ï ðñGêíì Bòêóð
éêëìê ëíê
One of these is designated as the start symbol. In this case it is (because we are
interested in generating sentences). Finally, the context-free grammar contains a finite set
,
of production rules, each of which consists of a pair, written
î
, where is one of the
non-terminals and is a string of terminals and non-terminals. In this case there are twelve
+ , +
productions, as shown on the slide.
46 6 GRAMMARS
The idea is that we begin with the start symbol -.#/0.$/$1(.
and use the productions to
continually replace non-terminal symbols by strings. At successive stages in this process we
have a string which may contain both terminals and non-terminals. We choose one of the
non-terminals in the string and a production which has that non-terminal as its left-hand side.
Replacing the non-terminal by the right-hand side of the production we obtain the next string
2
in the sequence, or derivation as it is called. The derivation stops when we obtain a string
containing only terminals. The set of strings over that may be obtained in this way from
the start symbol is by definition the language generated the context-free grammar.
A derivation
C(DFENMOPZRICZEICJLIHJ
VIW$WGXYP
is in this language, as witnessed by the derivation on Slide 36, in which we have indicated
left-hand sides of production rules by underlining. On the other hand, the string
(4) CDELXYPHI
is not in the language, because there is no derivation from -.#/0.$/$1(. to the string. (Why?)
Remark 6.1.1. The phrase ‘context-free’ refers to the fact that in a derivation we are allowed
to replace an occurrence of a non-terminal by the right-hand side of a production without
[
regard to the strings that occur on either side of the occurrence (its ‘context’). A more general
form of grammar (a ‘type grammar’ in the Chomsky hierarchy—see page 257 of Kozen’s
6.2 Backus-Naur Form 47
book, for example) has productions of the form ^\ ] _ \ _ are arbitrary strings of
where and
terminals and non-terminals. For example a production of the form
Terminals: n oqp r s t u
Non-terminals: vw x$y z n y
Start symbol: zny
Productions:
$v w |{ {~} n vw o
x$y |{ {~} qp rs
z n y |{ {~} v w z n yx$yz n y t z n y u
Slide 37
It is quite likely that the same non-terminal will appear on the left-hand side of several
productions in a context-free grammar. Because of this, it is common to use a more compact
notation for specifying productions, called Backus-Naur Form (BNF), in which all the
] ~
productions for a given non-terminal are specified together, with the different right-hand
sides being separated by the symbol ‘ ’. BNF also tends to use the symbol ‘ ’ rather than
‘ ’ in the notation for productions. An example of a context-free grammar in BNF is given
on Slide 37. Written out in full, the context-free grammar on this slide has eight productions,
48 6 GRAMMARS
namely:
S;
The language generated by this grammar is supposed to represent certain arithmetic expres-
sions. For example
(5)
T
is in the language, but
(6)
T
is not. (See Exercise 6.4.2.)
$¡ £¢¤
A context-free grammar for the language
Terminals:
Non-terminal: ¥
Start symbol: ¥
Productions: ¥§¦|¦~¨ª© ¥
Slide 38
6.3 Regular grammars 49
« ¬ ¬ «
A language over an alphabet is context-free iff is the set of strings generated by
½<¾ Í UË ¿ Ì Â Á Í Ë
¿ Î Æ ÆÆÏ~Í Ë
Í ¿ Ð Â ^¯ ÑÒÏÓÄÓÄÔÖÕ× ¾ Ç
Thus a string is in the language generated by the grammar iff it is accepted by Ê .
åçæ ì whenever
whenever
åîíðïQñ ñ ãÃòÈá ß
in
Slide 39
50 6 GRAMMARS
Theorem
Slide 40
It is possible to single out context-free grammars of a special form, called regular (or
right linear), which do generate regular languages. The definition is on Slide 40. Indeed, as
the theorem on that slide states, this type of grammar generates all possible regular languages.
û
Construction (Theorem on Slide 18), it is enough to construct an NFA with this property. þ
This makes the task much easier. We take the states of to be the non-terminals, augmented
by some extra states described below. Of course the alphabet of input symbols of should û
transitions and the accepting states of û
be the set of terminal symbols of the grammar. The start state is the start symbol. Finally, the
are defined as follows.
with
úý , say "! with
# $ #&%
(i) For each production of the form
, we add fresh states
ÿ
ÿ
ÿ'("ÿ)("ÿ*(+("ÿ,!
-. to the automaton and transitions
ÿ% /10 2ÿ 3% /54 ,ÿ *6% /7 888Û,ÿ !
-.3%:/5% >ÿ9
(ii) For each production of the form ; ÿ ÿ with 2
ú <ý >= , i.e. with ?A@ , we add an
@ -transition
ÿ %þ ÿ
6.4 Exercises 51
6.4 Exercises
Exercise 6.4.1. Why is the string (4) not in the language generated by the context-free
grammar in Section 6.1?
Exercise 6.4.2. Give a derivation showing that (5) is in the language generated by the
context-free grammar on Slide 37. Prove that (6) is not in that language. [Hint: show that
E
if is a string of terminals and non-terminals occurring in a derivation of this grammar and
~ E ~ \~~ \~~~
that ‘ ’ occurs in , then it does so in a substring of the form , or , or , etc., where is
either or .] )
V^z1
Exercise 6.4.3. Give a context-free grammar generating all the palindromes over the alphabet
(cf. Slide 28).
alphabet .
V^z_
Exercise 6.4.4. Give a context-free grammar generating all the regular expressions over the
Exercise 6.4.5. Using the construction given in the proof of part (a) of the Theorem on
Slide 40, convert the regular grammar with start symbol and productions B)
B,iCq
B,iC V
B,
B,iC BX
B2XC V
}
into an NFA whose language is that generated by the grammar.
Exercise 6.4.6. Is the language generated by the context-free grammar on Slide 35 a regular
language? What about the one on Slide 37?