কম্পিউটার বিজ্ঞান · বই 4 · স্নাতক দ্বিতীয় বর্ষ

University Computer Science — Year 2

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 2 · স্নাতক দ্বিতীয় বর্ষ

22Regular Expressions and the Limits of Regular Languages

A search box accepts a pattern: (a|a)*b asks for some aa’s, each written in one of two ways, then a bb. On a text of aa’s with no bb, Python’s pattern engine answers “no match”. The program times that answer:

"""backtracking.py: Python's re on (a|a)*b against a^n, which has no b: time per n."""
import subprocess
import sys

PROGRAM = """
import re, time
pattern, text = re.compile("(a|a)*b"), "a" * {n}
t = time.perf_counter()
assert pattern.match(text) is None             # every way of splitting is tried
print(time.perf_counter() - t)
"""

print("   n   time (s)   ratio to n - 1")
previous = None
for n in range(16, 28):
    try:                                         # each run in its own process, bounded
        run = subprocess.run([sys.executable, "-c", PROGRAM.format(n=n)],
                             capture_output=True, text=True, timeout=60)
        seconds = float(run.stdout)
    except subprocess.TimeoutExpired:
        print(f"{n:4}   over 60 s: stopped")
        break
    ratio = f"{seconds / previous:6.2f}" if previous else ""
    print(f"{n:4} {seconds:10.4f}   {ratio}".rstrip())
    previous = seconds
Listing 22.1. Timing one pattern on longer and longer texts, each run in its own bounded process code/bachelor-2/22-regular-languages/listings/backtracking.py
$ python backtracking.py
   n   time (s)   ratio to n - 1
  16     0.0033
  17     0.0067     2.01
  18     0.0130     1.96
  19     0.0255     1.96
  20     0.0574     2.25
  21     0.1125     1.96
  22     0.2097     1.86
  23     0.4259     2.03
  24     0.8915     2.09
  25     1.7003     1.91
  26     3.5214     2.07
  27     6.6253     1.88
Output 22.1. Python’s re on (a|a)*b and ana^n, on the laptop.

Each extra aa doubles the time: 27 letters take more than six seconds, and a search box that receives such a pattern freezes. The pattern is not hard. It means the same as a*b, and the previous chapter’s automata decide it in one step per letter. This chapter connects the two: patterns, called regular expressions, describe exactly the languages that finite automata recognise; every automaton has a smallest equivalent one, which is unique; and some simple languages, such as balanced brackets, are beyond both. It ends with a pattern engine that cannot freeze.

You already know

Chapter 21: words, languages, concatenation LMLM and star L∗L^*; deterministic automata (DFA), complete and trim; nondeterministic automata (NFA) with spontaneous transitions, which the subset construction turns into DFAs, at a cost of up to 2k2^k states; the product automaton, so that recognisable languages are closed under union, intersection and complement. The Year 1 volume: structural induction on trees, proving a property for leaves and then for each node from its children.

22.1 Regular expressions

Definition 22.1 (Regular expression, denoted language)

The regular expressions over an alphabet Σ\Sigma are the trees built by these rules: ∅\emptyset and ε\varepsilon are expressions, every letter a∈Σa \in \Sigma is an expression, and if ee and ff are expressions, so are e∣fe \mid f (alternation), efef (concatenation) and e∗e^* (star). The language denoted by an expression is defined on the tree: L(∅)=∅L(\emptyset) = \emptyset, L(ε)={ε}L(\varepsilon) = \{\varepsilon\}, L(a)={a}L(a) = \{a\}, L(e∣f)=L(e)∪L(f)L(e \mid f) = L(e) \cup L(f), L(ef)=L(e)L(f)L(ef) = L(e) L(f) and L(e∗)=L(e)∗L(e^*) = L(e)^*. Two expressions are equivalent if they denote the same language.

Written on one line, star binds tighter than concatenation, which binds tighter than alternation: ab∗∣cab^* \mid c is (a(b∗))∣c(a(b^*)) \mid c. The size of an expression is the number of nodes of its tree. So (a∣b)∗abb(a \mid b)^*abb denotes the words over {a,b}\{a, b\} that end with abbabb, and (ab∣b)∗(ab \mid b)^* the words in which every aa is followed by a bb. The library of this chapter’s listings, regex.rs, holds the tree as a Rust enumeration with six cases, and its function lang is the definition run, cut at a length nn so that the sets stay finite:

/// The denotation, cut to the words of length at most n: the definition, run.
pub fn lang(re: &Re, n: usize) -> BTreeSet<String> {
    match re {
        Re::Empty => BTreeSet::new(),
        Re::Eps => BTreeSet::from([String::new()]),
        Re::Char(c) => if n >= 1 { BTreeSet::from([c.to_string()]) } else { BTreeSet::new() },
        Re::Alt(x, y) => lang(x, n).union(&lang(y, n)).cloned().collect(),
        Re::Cat(x, y) => {
            let (lx, ly) = (lang(x, n), lang(y, n));
            lx.iter().flat_map(|u| ly.iter().filter(move |v| u.len() + v.len() <= n)
                .map(move |v| format!("{u}{v}"))).collect()
        }
        Re::Star(x) => {
            let lx = lang(x, n);
            let mut all = BTreeSet::from([String::new()]);
            let mut frontier = all.clone();
            while !frontier.is_empty() { // add one more factor until nothing new fits
                let next: BTreeSet<String> = frontier.iter()
                    .flat_map(|u| lx.iter().filter(move |v| u.len() + v.len() <= n)
                        .map(move |v| format!("{u}{v}")))
                    .filter(|w| !all.contains(w)).collect();
                all.extend(next.iter().cloned());
                frontier = next;
            }
            all
        }
    }
}
Listing 22.2. The denotation, by induction on the tree; the star adds one more factor until nothing new fits code/bachelor-2/22-regular-languages/listings/regex.rs

It is slow, since it builds every word, but it is obviously right, and the tests check the fast code against it.

Definition 22.2 (Regular language)

A language is regular if some regular expression denotes it. Equivalently, the regular languages form the smallest class of languages that contains ∅\emptyset, {ε}\{\varepsilon\} and every {a}\{a\}, and is closed under union, concatenation and star.

The two descriptions agree by structural induction: every denoted language is in any such class, and the denoted languages form such a class. Every finite language is regular: {w1,…,wk}\{w_1, \dots, w_k\} is denoted by w1∣⋯∣wkw_1 \mid \cdots \mid w_k.

Definition 22.3 (Extended regular expression)

An extended regular expression also uses these abbreviations: a class [abc] for a∣b∣ca \mid b \mid c and a range [a-z] for every letter from a to z; e+e^+ for ee∗ee^*; e?e? for e∣εe \mid \varepsilon; and the counts e{m,n}e\{m,n\} for mm copies of ee followed by n−mn - m copies of e?e?, with e{m}=e{m,m}e\{m\} = e\{m,m\}.

Each abbreviation is an ordinary expression, so extended expressions denote regular languages too; but they can be much shorter: (a∣b){20}(a \mid b)\{20\} stands for an expression with 40 letters. The parser of regex.rs reads them by recursive descent, one function per priority level; the function for the postfix operators expands them on the spot:

fn parse_post(s: &[char], pos: &mut usize) -> Result<Re, String> {
    let mut re = parse_atom(s, pos)?;
    while *pos < s.len() {
        re = match s[*pos] {
            '*' => Re::Star(Box::new(re)),
            '+' => Re::Cat(Box::new(re.clone()), Box::new(Re::Star(Box::new(re)))), // xx*
            '?' => Re::Alt(Box::new(re), Box::new(Re::Eps)), // x|ε
            '{' => {
                let close = s[*pos..].iter().position(|&c| c == '}').ok_or("no '}'")? + *pos;
                let body: String = s[*pos + 1..close].iter().collect();
                let (m, n) = match body.split_once(',') {
                    Some((m, n)) => (m.parse(), n.parse()),
                    None => (body.parse(), body.parse()),
                };
                let bad = |_| "bad count";
                let (m, n): (usize, usize) = (m.map_err(bad)?, n.map_err(bad)?);
                *pos = close;
                repeat(&re, m, n) // m copies, then n - m optional ones
            }
            _ => break,
        };
        *pos += 1;
    }
    Ok(re)
}
Listing 22.3. Postfix operators: star, plus, option and counts, each rewritten into the basic syntax code/bachelor-2/22-regular-languages/listings/regex.rs

The syntax here is a small one. Practical pattern languages add a wildcard for any character, anchors for the start and end of a line, and often back-references, which ask a later part of the text to repeat what an earlier group matched. Back-references go beyond regular languages (Section 22.4); the other additions do not.

22.2 Kleene’s theorem

Expressions describe languages; automata recognise them. This section turns each into the other.

Method 22.4 (Thompson’s construction)

For each node of the expression’s tree, build an NFA fragment with spontaneous transitions, one entry state ii and one exit state oo, no transition into ii and none out of oo, by induction on the tree as drawn below:

  • for ∅\emptyset: two states and no transition; for ε\varepsilon: i→εoi \xrightarrow{\varepsilon} o; for a letter: i→aoi \xrightarrow{a} o;
  • for efef: ii to the entry of ee, the exit of ee to the entry of ff, the exit of ff to oo, all spontaneous;
  • for e∣fe \mid f: spontaneous moves from ii to both entries and from both exits to oo;
  • for e∗e^*: spontaneous moves from ii to the entry of ee and to oo, and from the exit of ee back to its entry and to oo.

The fragment of the whole expression, with ii as start and oo as only accepting state, recognises L(e)L(e). It has two states per node, 2s2s for an expression of size ss, and at most two transitions leave each state.

Thompson’s fragments. A box is the fragment of a subexpression, entered on its left and left on its right; every arrow but the letter’s is a spontaneous transition.
Thompson’s fragments. A box is the fragment of a subexpression, entered on its left and left on its right; every arrow but the letter’s is a spontaneous transition.

Correctness is a structural induction: a path from ii to oo reads exactly a word of the subexpression’s language, since the only way out of a fragment is through its exit, which no transition leaves inside it. Thompson’s automaton is easy to build but full of spontaneous moves. Glushkov’s has none, and only one state per letter.

Definition 22.5 (Linear expression, local language)

An expression is linear if each letter occurs in it at most once. A language LL is local if there are sets P,S⊆ΣP, S \subseteq \Sigma and F⊆Σ2F \subseteq \Sigma^2 such that L∖{ε}L \setminus \{\varepsilon\} is the set of nonempty words whose first letter is in PP, whose last letter is in SS, and whose factors of length 2 are all in FF.

Whether a word belongs to a local language is decided by a window of two letters slid along it. Any expression is made linear by numbering its letters from the left, its positions: (a∣b)∗abb(a \mid b)^*abb becomes (a1∣b2)∗a3b4b5(a_1 \mid b_2)^* a_3 b_4 b_5. Erasing the numbers maps the linear expression’s language onto the original one.

Definition 22.6 (Glushkov automaton)

Let ee have positions 1,…,m1, \dots, m, the letter at position jj being ℓ(j)\ell(j), and let e′e' be the linear expression. Define Null\mathrm{Null} (whether ε∈L(e)\varepsilon \in L(e)), First\mathrm{First} (the positions that can begin a word of L(e′)L(e')), Last\mathrm{Last} (those that can end one), and Follow(j)\mathrm{Follow}(j) (the positions that can come right after jj in a word of L(e′)L(e')). The Glushkov automaton of ee has states 0,1,…,m0, 1, \dots, m, start state 0, transitions 0→ℓ(j)j0 \xrightarrow{\ell(j)} j for j∈Firstj \in \mathrm{First} and i→ℓ(j)ji \xrightarrow{\ell(j)} j for j∈Follow(i)j \in \mathrm{Follow}(i), and accepting states Last\mathrm{Last}, plus 0 if Null\mathrm{Null}.

Method 22.7 (The Berry–Sethi computation)

Compute Null\mathrm{Null}, First\mathrm{First} and Last\mathrm{Last} for every subexpression, bottom up: a position jj has (false,{j},{j})(\mathrm{false}, \{j\}, \{j\}); for ε\varepsilon, (true,∅,∅)(\mathrm{true}, \emptyset, \emptyset); an alternation takes the or and the unions; a concatenation fgfg has Null=Null(f)∧Null(g)\mathrm{Null} = \mathrm{Null}(f) \wedge \mathrm{Null}(g), First=First(f)\mathrm{First} = \mathrm{First}(f), joined by First(g)\mathrm{First}(g) if ff is nullable, and symmetrically for Last\mathrm{Last}; a star is nullable with its body’s sets. On the way, at each concatenation fgfg add First(g)\mathrm{First}(g) to Follow(j)\mathrm{Follow}(j) for every j∈Last(f)j \in \mathrm{Last}(f), and at each star f∗f^* add First(f)\mathrm{First}(f) to Follow(j)\mathrm{Follow}(j) for every j∈Last(f)j \in \mathrm{Last}(f).

The walk of regex.rs is this method, one case per kind of node:

/// Berry and Sethi: nullable, first and last of each subexpression, bottom up,
/// adding to follow at each concatenation and each star.
fn walk(re: &Re, g: &mut Glushkov) -> Sets {
    let none = BTreeSet::new;
    match re {
        Re::Empty => (false, none(), none()),
        Re::Eps => (true, none(), none()),
        Re::Char(c) => {
            g.letters.push(*c);
            g.follow.push(none());
            let j = g.letters.len(); // the next position
            (false, BTreeSet::from([j]), BTreeSet::from([j]))
        }
        Re::Alt(x, y) => {
            let ((nx, fx, lx), (ny, fy, ly)) = (walk(x, g), walk(y, g));
            (nx || ny, &fx | &fy, &lx | &ly)
        }
        Re::Cat(x, y) => {
            let ((nx, fx, lx), (ny, fy, ly)) = (walk(x, g), walk(y, g));
            for &j in &lx {
                g.follow[j].extend(fy.iter()); // the end of x, then the start of y
            }
            let first = if nx { &fx | &fy } else { fx };
            let last = if ny { &lx | &ly } else { ly };
            (nx && ny, first, last)
        }
        Re::Star(x) => {
            let (_, fx, lx) = walk(x, g);
            for &j in &lx {
                g.follow[j].extend(fx.iter()); // the end of x, then x again
            }
            (true, fx, lx)
        }
    }
}
Listing 22.4. The Berry–Sethi computation: three values per subexpression, and the follow sets filled at each concatenation and each star code/bachelor-2/22-regular-languages/listings/regex.rs
$ rustc --edition 2021 -O -o glushkov glushkov.rs && ./glushkov
positions: a1 b2 a3 b4 b5   nullable: false
first: {1, 2, 3}   last: {5}
follow(1) = {1, 2, 3}
follow(2) = {1, 2, 3}
follow(3) = {4}
follow(4) = {5}
follow(5) = {}
511 of 511 words up to length 8 judged as the definition says
Output 22.2. The positions and sets of (a∣b)∗abb(a \mid b)^*abb, and the automaton checked against the denotation.
The Glushkov automaton of (a b)*abb: one state per position, and every transition into a position carries that position’s letter. It is nondeterministic: from 0, a_1 and a_3 both read a.
The Glushkov automaton of (a∣b)∗abb(a \mid b)^*abb: one state per position, and every transition into a position carries that position’s letter. It is nondeterministic: from 0, a1a_1 and a3a_3 both read aa.

Proposition 22.8 (Glushkov’s automaton)

The Glushkov automaton of an expression with mm positions has m+1m + 1 states, no spontaneous transition, and at most m(m+1)m(m + 1) transitions, and it recognises L(e)L(e).

Proof. The counts come from the definition. For the language, first show by structural induction that L(e′)L(e') is local with P=FirstP = \mathrm{First}, S=LastS = \mathrm{Last} and F={ij:j∈Follow(i)}F = \{ij : j \in \mathrm{Follow}(i)\}, and that the sets computed by Method 22.7 are these. For a position, both are clear. For f∣gf \mid g, the positions of ff and gg are disjoint, no follow pair joins them, so a nonempty word passing the window test uses the positions of one side only and belongs to it. For fgfg, a word passing the test splits at the only pair ijij with ii in ff and jj in gg, which the method added exactly for i∈Last(f)i \in \mathrm{Last}(f), j∈First(g)j \in \mathrm{First}(g); the two parts pass the tests of ff and gg, or one part is empty and its side nullable. For f∗f^*, a word passing the test splits at the pairs ijij with i∈Last(f)i \in \mathrm{Last}(f), j∈First(f)j \in \mathrm{First}(f) added by the star, into words of L(f′)L(f'); and conversely every word of these languages passes the test. Finally, a run of the automaton on w=a1⋯akw = a_1 \cdots a_k from 0 visits positions j1,…,jkj_1, \dots, j_k with ℓ(jt)=at\ell(j_t) = a_t, j1∈Firstj_1 \in \mathrm{First} and each jt+1∈Follow(jt)j_{t+1} \in \mathrm{Follow}(j_t); it accepts when jk∈Lastj_k \in \mathrm{Last} (or k=0k = 0 and Null\mathrm{Null}). So the automaton accepts ww exactly when ww is the image of a word of the local language L(e′)L(e'), that is, w∈L(e)w \in L(e). ∎

Thompson’s automaton for (a∣b)∗abb(a \mid b)^*abb has 20 states; Glushkov’s has 6:

$ rustc --edition 2021 -O -o thompson thompson.rs && ./thompson
expression          Thompson states  Glushkov states  agree up to length 7
(a|b)*abb                        20                6  true
a*b*c*                           16                4  true
(ab|b)*                          12                4  true
((a|b)(a|b))*                    16                5  true
a?b?c                            18                4  true
Output 22.3. Thompson’s construction, two states per node of the tree, against Glushkov’s m+1m + 1, and the two automata compared on every word of length at most 7.

The way back, from an automaton to an expression, labels transitions with expressions and removes the states one by one.

Method 22.9 (State elimination)

Given an automaton with states 1,…,n1, \dots, n, add a new start SS with S→εS \xrightarrow{\varepsilon} the old start and a new end EE with q→εEq \xrightarrow{\varepsilon} E for every accepting qq. Label each pair (i,j)(i, j) by an expression rijr_{ij}: the alternation of the letters from ii to jj, or ∅\emptyset. Then, for k=1,…,nk = 1, \dots, n, remove state kk: for every pair (i,j)(i, j) of remaining states, replace

rijbyrij∣rik rkk∗ rkj.r_{ij} \quad\text{by}\quad r_{ij} \mid r_{ik}\, r_{kk}^*\, r_{kj}.

At the end only SS and EE remain, and rSEr_{SE} denotes the language of the automaton.

State elimination in three steps. Removing 0 reroutes S 0 1 into a*b (the loop a on 0 becomes a*) and 1 0 1 into aa*b, joined to the loop b.
State elimination in three steps. Removing 0 reroutes S→0→1S \to 0 \to 1 into a∗ba^*b (the loop aa on 0 becomes a∗a^*) and 1→0→11 \to 0 \to 1 into aa∗baa^*b, joined to the loop bb.

The loop in dfa.rs, the second library of the chapter, is the formula of the method; the smart constructors cat, alt and star of regex.rs drop the ∅\emptyset and ε\varepsilon that would otherwise fill the result:

/// State elimination: edges labelled by expressions, a new start S and end E; remove
/// the states one by one, rerouting every path through the removed state.
pub fn eliminate(d: &Dfa) -> Re {
    let n = d.delta.len();
    let (s, e) = (n, n + 1);
    let mut r = vec![vec![Re::Empty; n + 2]; n + 2];
    for (q, row) in d.delta.iter().enumerate() {
        for (a, &t) in row.iter().enumerate() {
            r[q][t] = alt(r[q][t].clone(), Re::Char(d.alphabet[a]));
        }
        if d.accept[q] {
            r[q][e] = Re::Eps;
        }
    }
    r[s][0] = Re::Eps;
    for k in 0..n {
        let loop_k = star(r[k][k].clone());
        for i in k + 1..n + 2 {
            for j in k + 1..n + 2 {
                let through = cat(cat(r[i][k].clone(), loop_k.clone()), r[k][j].clone());
                r[i][j] = alt(r[i][j].clone(), through); // i -> k, loops on k, k -> j
            }
        }
    }
    r[s][e].clone()
}
Listing 22.5. State elimination on a complete DFA code/bachelor-2/22-regular-languages/listings/dfa.rs
$ rustc --edition 2021 -O -o eliminate eliminate.rs && ./eliminate
expression: 0*|0*1(10*1)*10*|0*1(10*1)*0(1|0(10*1)*0)*0(10*1)*10*
matches exactly the multiples of 3 among 0 .. 4095: true
Output 22.4. The three-state automaton of the binary multiples of 3 (Chapter 21), turned into an expression and checked.

Theorem 22.10 (Kleene’s theorem)

A language is regular if and only if it is recognisable by a finite automaton.

Proof. If L=L(e)L = L(e), the Glushkov automaton recognises it (Proposition 22.8). Conversely, take an automaton and run Method 22.9. By induction on kk: after states 1,…,k1, \dots, k are removed, rijr_{ij} denotes the set of words that lead from ii to jj through intermediate states among 1,…,k1, \dots, k only. True for k=0k = 0, where there is no intermediate state. A path from ii to jj through 1,…,k1, \dots, k either avoids kk, and is counted by the old rijr_{ij}, or cuts at its visits to kk into a piece from ii to kk, any number of loops from kk to kk, and a piece from kk to jj, each avoiding kk inside: that is rikrkk∗rkjr_{ik} r_{kk}^* r_{kj}. At the end, rSEr_{SE} denotes the words leading from SS to EE, which are the accepted words. ∎

With Chapter 21, regular languages are therefore closed under complement and intersection too, though expressions have no operator for either: the way goes through automata.

History

Stephen Kleene introduced regular expressions and proved the theorem in his paper of 1956 on nerve nets and finite automata. Victor Glushkov’s position automaton appeared in his 1961 survey of the theory of automata. Ken Thompson published his construction in 1968, in a short paper on searching text for a regular expression, where the NFA is simulated on all its states at once. Gérard Berry and Ravi Sethi showed in 1986 how to compute the positions’ sets on the expression directly, as in Method 22.7.

22.3 The minimal automaton

Many automata recognise the same language. What a DFA must remember after reading uu is what the rest of the word needs to know.

Definition 22.11 (Residual, Myhill–Nerode equivalence)

The residual (or left quotient) of a language LL by a word uu is u−1L={v:uv∈L}u^{-1}L = \{v : uv \in L\}. Two words are equivalent for LL, u∼Lvu \sim_L v, if u−1L=v−1Lu^{-1}L = v^{-1}L: no continuation xx tells them apart, ux∈L  ⟺  vx∈Lux \in L \iff vx \in L.

For L=(ab∣b)∗L = (ab \mid b)^*: ε−1L=L\varepsilon^{-1}L = L, a−1L=bLa^{-1}L = bL, (aa)−1L=∅(aa)^{-1}L = \emptyset, and b−1L=(ab)−1L=Lb^{-1}L = (ab)^{-1}L = L. Every word has one of these three residuals.

Theorem 22.12 (Myhill–Nerode)

A language LL is recognisable if and only if it has finitely many residuals. Every complete DFA for LL has at least as many accessible states as LL has residuals, and the residual automaton reaches the bound: its states are the residuals, its start is LL, its transitions are R→aa−1RR \xrightarrow{a} a^{-1}R, and its accepting states are the residuals that contain ε\varepsilon.

Proof. Let AA be a complete DFA for LL and LqL_q the language it accepts from state qq. Then u−1L=Lδ∗(q0,u)u^{-1}L = L_{\delta^*(q_0, u)}: uvuv is accepted exactly when vv leads δ∗(q0,u)\delta^*(q_0, u) to an accepting state (Proposition 21.5). So each residual is LqL_q for some accessible qq, and there are at most as many residuals as accessible states. Conversely, suppose there are finitely many residuals. Since a−1(u−1L)=(ua)−1La^{-1}(u^{-1}L) = (ua)^{-1}L, the transitions of the residual automaton lead from a residual to a residual, and by induction on ∣w∣|w| its run on ww from LL ends in w−1Lw^{-1}L. It accepts ww when ε∈w−1L\varepsilon \in w^{-1}L, that is, when w∈Lw \in L. ∎

Definition 22.13 (Minimal automaton)

A complete DFA for LL is minimal if no complete DFA for LL has fewer states. By the theorem, the residual automaton is minimal; it is called the minimal automaton of LL.

Corollary 22.14 (Uniqueness)

Every minimal complete DFA for LL equals the residual automaton up to the names of its states.

Proof. In a minimal DFA AA every state is accessible, or removing it would leave a smaller complete DFA. The map q↦Lqq \mapsto L_q sends each state to a residual, reaches them all, and so is a bijection, since both sets have the same size. It respects the start (Lq0=LL_{q_0} = L), the accepting states (q∈Fq \in F iff ε∈Lq\varepsilon \in L_q) and the transitions (Lδ(q,a)=a−1LqL_{\delta(q, a)} = a^{-1}L_q). ∎

Two states pp and qq of a DFA can be merged when Lp=LqL_p = L_q. Moore’s method finds these pairs by looking further and further ahead.

Method 22.15 (Moore’s minimisation)

Start from an accessible complete DFA with nn states. Round 0 splits the states into two classes, accepting or not. Round k+1k + 1 puts pp and qq in the same class when they were in the same class at round kk and, for every letter aa, so were δ(p,a)\delta(p, a) and δ(q,a)\delta(q, a). Stop at the first round that splits no class. Merging each final class into one state gives the minimal automaton.

Correctness. By induction on kk, pp and qq share a class at round kk exactly when no word of length at most kk is accepted from one and not from the other. A round that splits nothing gives the same partition at every later round, since a round depends only on the previous one; so the final classes are those of Lp=LqL_p = L_q. Merging them gives a well defined DFA, since equivalent states have equivalent successors, with one state per residual of LL: the minimal automaton. Each round but the last adds a class, and there are at most nn, so there are at most nn rounds, each in time proportional to n∣Σ∣n|\Sigma|. ∎

/// Moore: start from {accepting, other}; split classes by the classes of the successors
/// until nothing splits. Returns the class of each state after each round.
pub fn moore(d: &Dfa) -> Vec<Vec<usize>> {
    let renumber = |keys: Vec<Vec<usize>>| {
        let mut seen = HashMap::new();
        keys.into_iter().map(|k| {
            let n = seen.len();
            *seen.entry(k).or_insert(n) // a new key gets the next number
        }).collect()
    };
    let first = d.accept.iter().map(|&a| vec![a as usize]).collect();
    let mut rounds: Vec<Vec<usize>> = vec![renumber(first)];
    loop {
        let class = rounds.last().unwrap();
        let keys = (0..d.delta.len())
            .map(|q| {
                let succ = d.delta[q].iter().map(|&r| class[r]);
                std::iter::once(class[q]).chain(succ).collect() // own class, then successors'
            })
            .collect();
        let next: Vec<usize> = renumber(keys);
        let count = |c: &Vec<usize>| c.iter().max().map_or(0, |m| m + 1);
        if count(&next) == count(class) {
            return rounds; // stable: the classes are those of the minimal automaton
        }
        rounds.push(next);
    }
}
Listing 22.6. Moore’s rounds: a state’s new class is named by its old class and its successors’ classes code/bachelor-2/22-regular-languages/listings/dfa.rs

The determinised Glushkov automaton of “starts with aa, or starts and ends with bb” has 7 states; two rounds leave 4 classes:

$ rustc --edition 2021 -O -o minimise minimise.rs && ./minimise
state  on a  on b  accepting
    0     1     2  false
    1     3     4  true
    2     5     6  true
    3     3     4  true
    4     3     4  true
    5     5     6  false
    6     5     6  true
round 0: classes [0, 1, 1, 1, 1, 0, 1]
round 1: classes [0, 1, 2, 1, 1, 3, 2]
minimal automaton: 4 states, from 7
Output 22.5. The DFA of a(a∣b)∗∣b(a∣b)∗b∣ba(a \mid b)^* \mid b(a \mid b)^*b \mid b, Moore’s classes round by round, and the result.
The minimal automaton: each state is a class of . In \2, 6\ the last letter read is a b after a first b; in \5\ it is an a.
The minimal automaton: each state is a class of Output 22.5. In {2,6}\{2, 6\} the last letter read is a bb after a first bb; in {5}\{5\} it is an aa.

Moore’s method can need nn rounds, on an automaton shaped as a chain, and then costs time proportional to n2∣Σ∣n^2|\Sigma|. John Hopcroft’s algorithm reaches n∣Σ∣log⁡nn |\Sigma| \log n: it keeps a list of splitters, a class and a letter, splits every class by “enters the splitter on that letter or not”, and when a class splits in two puts only the smaller half on the list. A state then joins a splitter at most log⁡2n\log_2 n times, since each time its class at least halves (Exercise 22.11).

22.4 The limits of regular languages

A finite automaton has a finite memory. A language that needs to count without bound is not regular.

Theorem 22.16 (Pumping lemma)

If LL is recognised by a DFA with pp states, every word w∈Lw \in L with ∣w∣≥p|w| \ge p can be written w=xyzw = xyz with ∣xy∣≤p|xy| \le p and y≠εy \ne \varepsilon, so that xykz∈Lxy^kz \in L for every k≥0k \ge 0.

Proof. The run on the first pp letters of ww visits p+1p + 1 states, so one state qq appears twice, after reading xx and after reading xyxy, with ∣xy∣≤p|xy| \le p and yy nonempty. Reading yy leads qq back to qq, so it can be read any number of times, zero included, and the run on xykzxy^kz ends where the run on ww ends, in an accepting state. ∎

Proposition 22.17 (Three languages that are not regular)

The languages {anbn:n≥0}\{a^n b^n : n \ge 0\}, the balanced bracket words over {(,)}\{(, )\}, and the palindromes over {a,b}\{a, b\} are not regular.

Proof. For {anbn}\{a^nb^n\}, by the pumping lemma: if a DFA with pp states recognised it, w=apbpw = a^pb^p would split with y=ajy = a^j, j≥1j \ge 1, since ∣xy∣≤p|xy| \le p; but xy2z=ap+jbpxy^2z = a^{p+j}b^p is not in the language. Also by Theorem 22.12: for i≠ji \ne j, bib^i is in the residual by aia^i and not in the residual by aja^j, so the residuals are infinitely many. Balanced brackets: their intersection with the regular language (∗ )∗(^*\,)^* is {(n)n}\{(^n )^n\}, which is {anbn}\{a^nb^n\} with other letters; if they were regular, so would be the intersection. Palindromes: for i≠ji \ne j, baiba^i is in the residual by aiba^ib and not in the residual by ajba^jb. ∎

The pumping lemma gives only a necessary condition: some languages that are not regular can be pumped. The residuals give the exact answer, and with them a proof is a matter of finding infinitely many words that pairwise differ in what must follow. A back-reference that repeats a group asks for the language {ww}\{ww\}, which has infinitely many residuals (by aiba^ib, as for palindromes); this is why pattern engines with back-references cannot be finite automata. Balanced brackets and arithmetic expressions need the grammars of Chapter 23.

History

The equivalence and the theorem carry the names of John Myhill and Anil Nerode; Nerode’s paper appeared in 1958. The pumping lemma for regular languages is a direct form of the pigeonhole argument used in its proof.

22.5 Deciding questions about automata

Because an automaton is a finite object, many questions about the infinite language it recognises can be answered by a program that always stops.

Proposition 22.18 (Questions and their costs)

For complete DFAs AA and BB with nAn_A and nBn_B states over Σ\Sigma:

  • membership of a word ww: time proportional to ∣w∣|w|;
  • emptiness, L(A)=∅L(A) = \emptyset: no accepting state is accessible, a graph search in time proportional to nA∣Σ∣n_A|\Sigma|;
  • finiteness: L(A)L(A) is infinite exactly when the trim automaton has a cycle, also a graph search;
  • inclusion, L(A)⊆L(B)L(A) \subseteq L(B): L(A)∩(Σ∗∖L(B))L(A) \cap (\Sigma^* \setminus L(B)) is empty, a search of the product in time proportional to nAnB∣Σ∣n_A n_B |\Sigma|;
  • equivalence: no accessible pair (p,q)(p, q) of the product has pp accepting and qq not, or the reverse; a breadth-first search finds a shortest word on which they differ, if there is one.

Proof. Membership is the run. Emptiness: a word is accepted exactly when its run reaches an accepting state, so L(A)L(A) is nonempty exactly when an accepting state is accessible. Finiteness: in the trim automaton every path extends into an accepted word; a cycle gives infinitely many paths, and without a cycle every path has fewer than nAn_A transitions, so the accepted words are shorter than nAn_A and finitely many. Inclusion is emptiness of the product for intersection with the complement (Proposition 21.17), and equivalence is two inclusions, read on the same product: the pair after ww is (δA∗(qA,w),δB∗(qB,w))(\delta_A^*(q_A, w), \delta_B^*(q_B, w)), and ww separates the languages exactly when one of the two states accepts and the other does not. ∎

From expressions, these questions go through automata. The Glushkov automaton is built in time proportional to m2m^2 and decides membership by simulation in at most (m+1)∣w∣(m + 1)|w| steps; but inclusion and equivalence need complete DFAs, and determinisation may cost exponentially many states (Theorem 21.15). For short patterns it is fast:

$ rustc --edition 2021 -O -o equivalent equivalent.rs && ./equivalent
(a|b)*     = (a*b*)*
(ab)*a     = a(ba)*
a*b*       differs from (a|b)*: on "ba"
(a|b)*abb  differs from (a|b)*bb: on "bb"
(aa|a)*    = a*
Output 22.6. Five pairs of expressions, compared through their determinised Glushkov automata, with a shortest witness when they differ.

The witness "bb" is in the language of (a∣b)∗bb(a \mid b)^*bb but does not end with abbabb. The checker itself is Exercise 22.9. By Corollary 22.14, a second way to compare is to minimise both automata and compare them state by state.

22.6 A pattern engine that cannot freeze

The engine of regex.rs parses the pattern into a tree, computes Glushkov’s sets, and simulates the automaton on sets of states, as Chapter 21 simulated NFAs. With at most 127 positions, a set of states is the bits of one 128-bit integer; for each letter, the next set is the union of the successors of the current states, kept only at positions holding that letter:

impl Matcher {
    pub fn new(g: &Glushkov) -> Matcher {
        assert!(g.letters.len() < 128, "at most 127 positions");
        let bits = |s: &BTreeSet<usize>| s.iter().fold(0u128, |m, &j| m | 1 << j);
        let mut succ = vec![bits(&g.first)];
        succ.extend(g.follow[1..].iter().map(bits));
        let mut with = std::collections::HashMap::new();
        for (j, &c) in g.letters.iter().enumerate() {
            *with.entry(c).or_insert(0) |= 1u128 << (j + 1);
        }
        Matcher { succ, with, accept: bits(&g.last) | g.nullable as u128 }
    }

    /// Accept or not, and the number of steps: at most m + 1 ORs per letter.
    pub fn run(&self, word: &str) -> (bool, usize) {
        let (mut set, mut steps) = (1u128, 0); // {0}
        for c in word.chars() {
            let mut next = 0;
            let mut rest = set;
            while rest != 0 {
                next |= self.succ[rest.trailing_zeros() as usize];
                rest &= rest - 1;
                steps += 1;
            }
            set = next & self.with.get(&c).copied().unwrap_or(0);
        }
        (set & self.accept != 0, steps)
    }
Listing 22.7. The matcher: one OR per current state, then a mask for the letter code/bachelor-2/22-regular-languages/listings/regex.rs

Proposition 22.19 (Linear matching)

On an expression with mm positions and a text of nn letters, the matcher performs at most (m+1)n(m + 1)n unions, whatever the expression and the text.

Proof. Each letter costs one union per state of the current set, and the set holds at most the m+1m + 1 states. The set after kk letters is the set of states the Glushkov automaton can reach on the first kk letters, by induction on kk, so the answer is that of the automaton, which is correct by Proposition 22.8. ∎

On (a∣a)∗b(a \mid a)^*b, with positions a1a_1, a2a_2, b3b_3, the set after each aa is {1,2}\{1, 2\}, and every letter costs two unions:

$ rustc --edition 2021 -O -o engine_compare engine_compare.rs && ./engine_compare
        n   matched      steps   steps/letter   time (ms)
       20 false             39           1.95       0.000
       24 false             47           1.96       0.000
     1000 false           1999           2.00       0.007
  1000000 false        1999999           2.00       7.255
 10000000 false       19999999           2.00      73.370
Output 22.7. The matcher on (a∣a)∗b(a \mid a)^*b and ana^n, on the laptop.
Time to answer “no match” for (a a)*b on an, on a logarithmic scale: the backtracking engine’s points () climb on a straight line, doubling with each a; the matcher’s line is its measured cost per letter on ten million letters (), times n.
Time to answer “no match” for (a∣a)∗b(a \mid a)^*b on ana^n, on a logarithmic scale: the backtracking engine’s points (Output 22.1) climb on a straight line, doubling with each aa; the matcher’s line is its measured cost per letter on ten million letters (Output 22.7), times nn.

A backtracking engine tries one way to match at a time: on ana^n, each aa can be matched by the left or the right branch of (a∣a)(a \mid a), and when the missing bb makes a choice fail, the engine goes back to the last choice and tries the other. The 2n2^n ways to read ana^n all fail, and it tries them all. The automaton keeps every way at once, in a set that never holds more than m+1m + 1 states. Backtracking has reasons: it reports which part of the text each group matched, in the order a programmer expects, and it supports back-references, which no automaton can. Engines built on automata, in the line of Thompson’s, give up back-references and in exchange answer in linear time.

Facts as of 2026

Python’s re module is a backtracking engine. Since version 3.11 it offers possessive quantifiers such as a*+ and atomic groups, which throw away the backtracking points inside them and can stop a blow-up like the hook’s when the pattern’s author sees it coming. The POSIX standard defines basic and extended regular expressions for tools such as grep, and asks, when several matches start at the same point, for the longest.

On the town’s 24 street names, the engine answers patterns that expand to a hundred positions, since a range such as [A-Z] is an alternation of 26 letters:

// streets.rs: patterns over the town's street names.
#[allow(dead_code)]
mod regex;

fn main() {
    let table = std::fs::read_to_string("../../../../data/town/streets.csv").unwrap();
    let names: Vec<&str> = table.lines().skip(1)
        .map(|line| line.split(',').nth(1).unwrap()).collect();
    let patterns = ["[A-Z][a-z]* Road", "[A-Z][a-z]* (Road|Row|Way)",
                    "(Mill|River) [A-Za-z]*", "[A-Z][a-z]*(e|n) [A-Z][a-z]*",
                    "[A-Z][a-z]* [A-Z][a-z]*"];
    for pattern in patterns {
        let re = regex::parse(pattern).unwrap();
        let g = regex::glushkov(&re);
        let m = regex::Matcher::new(&g);
        let hits: Vec<&str> = names.iter().copied().filter(|n| m.matches(n)).collect();
        let some = hits.iter().take(2).copied().collect::<Vec<_>>().join(", ");
        let (m, k) = (g.letters.len(), hits.len());
        println!("{pattern:31} {m:3} positions {k:3} of {}: {some}", names.len());
    }
}
Listing 22.8. Five patterns over the street names code/bachelor-2/22-regular-languages/listings/streets.rs
$ rustc --edition 2021 -O -o streets streets.rs && ./streets
[A-Z][a-z]* Road                 57 positions   4 of 24: Bridge Road, Castle Road
[A-Z][a-z]* (Road|Row|Way)       63 positions  14 of 24: Bridge Road, Bridge Way
(Mill|River) [A-Za-z]*           62 positions   5 of 24: Mill Avenue, Mill Row
[A-Z][a-z]*(e|n) [A-Z][a-z]*    107 positions   8 of 24: Bridge Road, Bridge Way
[A-Z][a-z]* [A-Z][a-z]*         105 positions  24 of 24: Bridge Road, Bridge Way
Output 22.8. The number of positions of each pattern, the number of names it matches, and the first two.

22.7 Exercises

Exercise 22.1 ★

Which of the words ε\varepsilon, aa, aaaa, babbab, abbaabba, bababbabab, aabaab are in L((ab∣b)∗a?)L((ab \mid b)^*a?)? Describe the language in words, then check with the engine.

Solution

Solution of Exercise 22.1.

$ rustc --edition 2021 -O -o exo_match exo_match.rs && ./exo_match
""       true
"a"      true
"aa"     false
"bab"    true
"abba"   true
"babab"  true
"aab"    false
Output 22.9. The seven words.

(ab∣b)∗(ab \mid b)^* is the words in which every aa is immediately followed by a bb, and the final a?a? allows one more aa at the end. So ε\varepsilon, aa, babbab, abbaabba and bababbabab match; aaaa and aabaab do not, since their first aa is followed by an aa.

Exercise 22.2 ★

A tool checks variable names with the pattern [a-z0-9_]+. Find the names it wrongly accepts, and write a pattern that requires a first character that is not a digit.

Solution

Solution of Exercise 22.2.

$ rustc --edition 2021 -O -o exo_ident exo_ident.rs && ./exo_ident
"x"       [a-z0-9_]+ true    [a-z_][a-z0-9_]* true
"x9"      [a-z0-9_]+ true    [a-z_][a-z0-9_]* true
"9lives"  [a-z0-9_]+ true    [a-z_][a-z0-9_]* false
"_tmp"    [a-z0-9_]+ true    [a-z_][a-z0-9_]* true
"2"       [a-z0-9_]+ true    [a-z_][a-z0-9_]* false
""        [a-z0-9_]+ false   [a-z_][a-z0-9_]* false
Output 22.10. The two patterns on six names.

[a-z0-9_]+ accepts 9lives and 2, which start with a digit. The pattern [a-z_][a-z0-9_]* asks for one letter or underscore, then any number of letters, digits or underscores: it rejects them, and still rejects the empty name.

Exercise 22.3 ★

Write an extended expression for the decimal numbers of Chapter 21’s hook (an optional sign, digits, an optional point followed by digits, an optional exponent). Check it against the hook’s automaton on every string of length at most 6 over the characters 0 1 + - . e E; in this chapter’s syntax, . is a plain letter.

Solution

Solution of Exercise 22.3.

$ rustc --edition 2021 -O -o exo_decimal exo_decimal.rs && ./exo_decimal
137257 strings, 1854 numbers, 0 disagreements
Output 22.11. The expression against the hook’s automaton.

The expression is [+-]?[0-9]+(.[0-9]+)?([eE][+-]?[0-9]+)?: an optional sign, at least one digit, an optional group of a point and at least one digit, and an optional exponent with its own optional sign. It agrees with the automaton on all 137 257 strings of length at most 6 over the seven characters, 1 854 of which are numbers. A check on a finite set is not a proof; the proof is Exercise 22.9’s checker, run on the two automata.

Exercise 22.4 ★

Let cnc_n be the number of words of length nn in L((ab∣b)∗)L((ab \mid b)^*). Find a recurrence for cnc_n, and check it on c0,…,c12c_0, \dots, c_{12}.

Solution

Solution of Exercise 22.4.

$ rustc --edition 2021 -O -o exo_count exo_count.rs && ./exo_count
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
Output 22.12. c0c_0 to c12c_{12}, from the denotation.

A nonempty word of the language starts either with bb, followed by any word of the language of length n−1n - 1, or with abab, followed by one of length n−2n - 2; the two cases do not overlap, since the first letter tells them apart. So cn=cn−1+cn−2c_n = c_{n-1} + c_{n-2} with c0=c1=1c_0 = c_1 = 1: the Fibonacci numbers.

Exercise 22.5 ★★

Number the positions of a(ba∣b)∗aa(ba \mid b)^*a and compute Null\mathrm{Null}, First\mathrm{First}, Last\mathrm{Last} and every Follow\mathrm{Follow} set by Method 22.7. Draw the Glushkov automaton.

Solution

Solution of Exercise 22.5.

$ rustc --edition 2021 -O -o exo_follow exo_follow.rs && ./exo_follow
a1 b2 a3 b4 a5; nullable false; first {1}; last {5}
follow(1) = {2, 4, 5}
follow(2) = {3}
follow(3) = {2, 4, 5}
follow(4) = {2, 4, 5}
follow(5) = {}
Output 22.13. The sets of a1(b2a3∣b4)∗a5a_1(b_2a_3 \mid b_4)^*a_5.

The star’s body has First={2,4}\mathrm{First} = \{2, 4\} and Last={3,4}\mathrm{Last} = \{3, 4\}; the star adds {2,4}\{2, 4\} to the follow sets of 3 and 4. The concatenation of a1a_1 with the star (nullable) gives Follow(1)={2,4}\mathrm{Follow}(1) = \{2, 4\}, and the concatenation with a5a_5 adds 5 to the follow sets of 1, 3 and 4. Inside b2a3b_2a_3, Follow(2)={3}\mathrm{Follow}(2) = \{3\}. The automaton has states 0 to 5: 0→a10 \xrightarrow{a} 1; from 1, 3 and 4: bb to 2, bb to 4 and aa to 5; 2→a32 \xrightarrow{a} 3; state 5 accepts.

Exercise 22.6 ★★

A program minimises the incomplete DFA of {ab,ba}\{ab, ba\} (states 0, 1 after aa, 2 after bb, 3 accepting) by refining classes on the classes of the successors that exist, without completing it first. Which states does it merge, and which words does the merged automaton wrongly accept? How must the program be fixed?

Solution

Solution of Exercise 22.6.

$ rustc --edition 2021 -O -o exo_min_bug exo_min_bug.rs && ./exo_min_bug
classes: [0, 1, 1, 2]
ab: true
ba: true
aa: true
bb: true
Output 22.14. The classes found, and four words on the merged automaton.

States 1 and 2 both have one successor, in the accepting class, so the program merges them; it forgot that state 1 moves on bb and state 2 on aa. The merged automaton accepts aaaa and bbbb as well as abab and baba. The fix is to complete the automaton first, with a sink, and to compare the successors letter by letter, as in Listing 22.6: then 1 goes to the sink on aa and 2 goes to 3, and round 1 separates them.

Exercise 22.7 ★★

Apply Method 22.9 by hand to the two-state DFA of “an even number of aa” over {a,b}\{a, b\}, removing the start state first. Check the expression on every word of length at most 10.

Solution

Solution of Exercise 22.7.

$ rustc --edition 2021 -O -o exo_eliminate exo_eliminate.rs && ./exo_eliminate
b*|b*a(b|ab*a)*ab*
right on all 2047 words up to length 10: true
Output 22.15. The expression found by eliminate, and its check.

State 0 (even) is the start and accepts; r00=br_{00} = b, r01=ar_{01} = a, r10=ar_{10} = a, r11=br_{11} = b, with S→ε0S \xrightarrow{\varepsilon} 0 and 0→εE0 \xrightarrow{\varepsilon} E. Removing 0 gives rSE=b∗r_{SE} = b^*, rS1=b∗ar_{S1} = b^*a, r11=b∣ab∗ar_{11} = b \mid ab^*a and r1E=ab∗r_{1E} = ab^*. Removing 1 gives rSE=b∗∣b∗a(b∣ab∗a)∗ab∗r_{SE} = b^* \mid b^*a(b \mid ab^*a)^*ab^*: no aa, or a first aa, blocks with an even number of aa, and a last aa.

Exercise 22.8 ★★

Prove that {anbm:n≤m}\{a^n b^m : n \le m\} is not regular, once with the pumping lemma and once with residuals.

Solution

Solution of Exercise 22.8.

Let L={anbm:n≤m}L = \{a^nb^m : n \le m\}. Pumping: if a DFA with pp states recognised LL, then w=apbp∈Lw = a^pb^p \in L would split as xyzxyz with ∣xy∣≤p|xy| \le p, so y=ajy = a^j with j≥1j \ge 1, and xy2z=ap+jbpxy^2z = a^{p+j}b^p would be in LL; it is not, since p+j>pp + j > p. Residuals: for i<ji < j, bib^i is in (ai)−1L(a^i)^{-1}L but not in (aj)−1L(a^j)^{-1}L, so the words a0,a1,a2,…a^0, a^1, a^2, \dots have pairwise different residuals, infinitely many, and Theorem 22.12 concludes.

Exercise 22.9 ★★

Write a function that takes two complete DFAs over the same alphabet and returns either “equivalent” or a shortest word on which they differ. Use it to compare expressions through their Glushkov automata.

Solution

Solution of Exercise 22.9.

/// None if the two automata recognise the same language, else a shortest word on which
/// they differ: a breadth-first search over the pairs of states.
pub fn difference(x: &Dfa, y: &Dfa) -> Option<String> {
    let mut seen = HashMap::from([((0, 0), String::new())]);
    let mut todo = VecDeque::from([(0, 0)]);
    while let Some((p, q)) = todo.pop_front() {
        let w = seen[&(p, q)].clone();
        if x.accept[p] != y.accept[q] {
            return Some(w);
        }
        for (a, &c) in x.alphabet.iter().enumerate() {
            let next = (x.delta[p][a], y.delta[q][a]);
            if let std::collections::hash_map::Entry::Vacant(e) = seen.entry(next) {
                e.insert(format!("{w}{c}")); // a shortest word reaching this pair
                todo.push_back(next);
            }
        }
    }
    None
}
A breadth-first search over pairs of states code/bachelor-2/22-regular-languages/listings/dfa.rs

The search starts from the pair of start states and follows each letter in both automata at once: this is the product automaton, built only as far as it is reached. Each pair is entered once, with the word that first reached it; since a breadth-first search reaches pairs in order of the length of that word, the first pair with different acceptance gives a shortest word on which the languages differ. If no such pair is reached, the languages are equal (Proposition 22.18). The cost is at most nAnB∣Σ∣n_A n_B |\Sigma| steps. Output 22.6 shows it on five pairs of expressions.

Exercise 22.10 ★★★

Show that ∼L\sim_L is a right congruence: u∼Lvu \sim_L v implies ua∼Lvaua \sim_L va for every letter aa. Deduce that if LL is regular, the classes of ∼L\sim_L are in bijection with the states of the minimal automaton, u∼Lvu \sim_L v holding exactly when uu and vv lead it to the same state.

Solution

Solution of Exercise 22.10.

If u−1L=v−1Lu^{-1}L = v^{-1}L, then (ua)−1L=a−1(u−1L)=a−1(v−1L)=(va)−1L(ua)^{-1}L = a^{-1}(u^{-1}L) = a^{-1}(v^{-1}L) = (va)^{-1}L, since x∈(ua)−1Lx \in (ua)^{-1}L iff uax∈Luax \in L iff ax∈u−1Lax \in u^{-1}L. So ∼L\sim_L is a right congruence. By definition, the classes of ∼L\sim_L are in bijection with the residuals, by [u]↦u−1L[u] \mapsto u^{-1}L. By Corollary 22.14, the minimal automaton is the residual automaton, whose run on uu ends in u−1Lu^{-1}L (Theorem 22.12). So uu and vv lead it to the same state exactly when u−1L=v−1Lu^{-1}L = v^{-1}L, that is, when u∼Lvu \sim_L v, and the number of classes, the index of ∼L\sim_L, is the number of states of the minimal automaton.

Exercise 22.11 ★★★

Implement Hopcroft’s algorithm: keep a list of splitters (a class and a letter); for a splitter (B,a)(B, a), split each class into the states that enter BB on aa and the others; when a class splits, put both halves on the list if it was there, and otherwise only the smaller half. Check that it finds Moore’s classes, and compare the two on large automata. Why is the gain so small here?

Solution

Solution of Exercise 22.11.

    let smaller = (0..blocks.len()).min_by_key(|&i| blocks[i].len()).unwrap();
    let mut work: HashSet<(usize, usize)> = (0..k).map(|a| (smaller, a)).collect();
    let mut hit = vec![false; n]; // marks, cleared after each splitter
    while let Some(&(b, a)) = work.iter().next() {
        work.remove(&(b, a));
        let mut entering: Vec<usize> = blocks[b].iter() // the states entering b on a
            .flat_map(|&q| inv[a][q].iter().copied()).collect();
        entering.iter().for_each(|&p| hit[p] = true);
        entering.sort_by_key(|&p| block_of[p]);
        let mut touched: Vec<usize> = entering.iter().map(|&p| block_of[p]).collect();
        touched.dedup();
        for y in touched {
            let (inside, outside): (Vec<usize>, Vec<usize>) =
                blocks[y].iter().partition(|&&q| hit[q]);
            if outside.is_empty() {
                continue; // y lies entirely in the preimage: no split
            }
            let z = blocks.len(); // y keeps `inside`, the new block z gets `outside`
            outside.iter().for_each(|&q| block_of[q] = z);
            let small = if inside.len() <= outside.len() { y } else { z };
            blocks[y] = inside;
            blocks.push(outside);
            for c in 0..k {
                if work.contains(&(y, c)) {
                    work.insert((z, c)); // both halves still to be used
                } else {
                    work.insert((small, c)); // the smaller half is enough
                }
            }
        }
        entering.iter().for_each(|&p| hit[p] = false);
    }
Hopcroft’s loop: splitters, the states entering them, and the smaller half code/bachelor-2/22-regular-languages/exercises/hopcroft.rs
$ rustc --edition 2021 -O -o minimise_bench minimise_bench.rs && ./minimise_bench
 k   DFA states  minimal  Moore rounds  Moore (ms)  Hopcroft (ms)
 8          769      511             9         0.5            0.4
10         3073     2047            11         2.3            1.8
12        12289     8191            13        13.2            8.4
14        49153    32767            15        74.2           52.2
Output 22.16. Moore and Hopcroft on automata of up to 49 153 states, on the laptop.

The predecessor lists inv let a splitter (B,a)(B, a) cost the number of transitions entering BB on aa. A state qq lies in a splitter on the list once per time its class is put there, and after its first time it is put there only as the smaller half, at most half of the previous class: at most 1+log⁡2n1 + \log_2 n times per letter. Summed over the states, the work is proportional to n∣Σ∣log⁡nn|\Sigma| \log n. The tests check that the classes are Moore’s on every sample. Here Hopcroft’s algorithm gains less than a factor of 2 (between 1.25 and 1.6 in the run printed): Moore’s method needs only k+1k + 1 rounds on these automata, about log⁡2n\log_2 n, so both do about nlog⁡nn \log n work, and Hopcroft’s bookkeeping (a set of splitters, predecessor lists, sorting) costs more per step. On an automaton that is a chain of nn states, Moore needs about nn rounds and the difference becomes large.

Exercise 22.12 ★★★

Prove that {w∈{a,b}∗:w has as many a as b}\{w \in \{a, b\}^* : w \text{ has as many } a \text{ as } b\} is not regular, once with residuals and once by intersecting it with a∗b∗a^*b^*.

Solution

Solution of Exercise 22.12.

Let LL be the words with as many aa as bb. Residuals: for i≠ji \ne j, bi∈(ai)−1Lb^i \in (a^i)^{-1}L and bi∉(aj)−1Lb^i \notin (a^j)^{-1}L, so LL has infinitely many residuals. Intersection: L∩a∗b∗={anbn}L \cap a^*b^* = \{a^nb^n\}, which is not regular (Proposition 22.17); since a∗b∗a^*b^* is regular and regular languages are closed under intersection, LL cannot be regular.

22.8 Problem: A search box that never freezes

Problem 22.1

Weekend problem — A search box that never freezes

The town’s website lets visitors search the street names with patterns. The first version used a backtracking engine, and a visitor froze it. This problem builds the replacement. The 24 names are Bridge Road, Bridge Way, Castle Road, Castle Row, Castle Way, Church Lane, Church Way, Garden Lane, Garden Road, Market Road, Market Row, Mill Avenue, Mill Row, Mill Street, Orchard Lane, Orchard Row, Orchard Way, River Avenue, River Lane, School Avenue, School Lane, School Way, Station Row and Willow Lane.

Part I — Patterns over the street names.

  1. How many names end in Road, in Row and in Way? Compare with Output 22.8.
  2. Why does [A-Z][a-z]* Road have 57 positions?
  3. Write a pattern for the names whose second word is Lane or Avenue. How many names does it match?
  4. List the 8 names matched by [A-Z][a-z]*(e|n) [A-Z][a-z]*.
  5. Show that any finite set of names is a regular language.
  6. A search box looks for the pattern anywhere in a name. Which expression, built from ee, denotes the names that contain a match of ee?

Part II — The Glushkov engine.

Let e=(ab∣b)∗ce = (ab \mid b)^*c over {a,b,c}\{a, b, c\}.

  1. Number the positions of ee and give Null\mathrm{Null}, First\mathrm{First}, Last\mathrm{Last} and the follow sets.
  2. How many states and transitions does its Glushkov automaton have?
  3. Give the matcher’s set of states after each letter of babbcbabbc. Is the word accepted, and how many unions were made?
  4. Show that after reading a letter, every state in the set is a position holding that letter.
  5. At most how many unions does the matcher make on a name of 12 letters with the pattern [A-Z][a-z]* Road?
  6. Why does the matcher refuse patterns with more than 127 positions, and how would you lift the limit?

Part III — One automaton per language.

  1. Determinise the Glushkov automaton of ee over {a,b,c}\{a, b, c\}, with the empty set as sink. How many states?
  2. Apply Moore’s method to it. How many rounds, and how many classes at the end?
  3. List the residuals of L(e)L(e), and match them with the final classes.
  4. Show that (ab∣b)∗c(ab \mid b)^*c and b∗(abb∗)∗cb^*(abb^*)^*c are equivalent.
  5. Find a shortest word on which (ab∣b)∗c(ab \mid b)^*c and (a∣b)∗bc(a \mid b)^*bc differ.
  6. The site stores compiled patterns in a cache. Why can two patterns that denote the same language share one entry, and how can a key be computed for it?

Part IV — Backtracking against the automaton.

  1. In how many ways can ana^n be read as a sequence of matches of (a∣a)(a \mid a)?
  2. Why does a backtracking engine try all of them on ana^n? Relate this to the ratios of Output 22.1.
  3. From the hook’s last line, estimate how long the old site would take for 40 letters.
  4. How many unions does the matcher make on ana^n with (a∣a)∗b(a \mid a)^*b? Check with Output 22.7.
  5. How long does the matcher take for 40 letters, and for ten million?
  6. State the result: from exponential to linear, backtracking’s time doubling with each aa, measured, against at most (m+1)n(m + 1)n steps proved for the automaton.
Solution

Solution of Problem 22.1.

1. 4 end in Road, 5 in Row and 5 in Way: the 14 of the second line.

2. [A-Z] is an alternation of 26 letters, [a-z]* the star of 26 more, then the space and the four letters of Road: 26+26+1+4=5726 + 26 + 1 + 4 = 57.

3. [A-Z][a-z]* (Lane|Avenue): the 6 lanes and the 3 avenues, 9 names.

4. Bridge Road, Bridge Way, Castle Road, Castle Row, Castle Way, Garden Lane, Garden Road, Station Row.

5. The alternation of the names, each written as a concatenation of its letters, denotes the set.

6. Σ∗eΣ∗\Sigma^* e \Sigma^*, with Σ\Sigma written as a class of every character that can occur in a name.

7. a1b2b3c4a_1 b_2 b_3 c_4; Null\mathrm{Null} is false, First={1,3,4}\mathrm{First} = \{1, 3, 4\}, Last={4}\mathrm{Last} = \{4\}, Follow(1)={2}\mathrm{Follow}(1) = \{2\}, Follow(2)=Follow(3)={1,3,4}\mathrm{Follow}(2) = \mathrm{Follow}(3) = \{1, 3, 4\}, Follow(4)=∅\mathrm{Follow}(4) = \emptyset.

8. 5 states, and 3+1+3+3+0=103 + 1 + 3 + 3 + 0 = 10 transitions.

9. {0}→b{3}→a{1}→b{2}→b{3}→c{4}\{0\} \xrightarrow{b} \{3\} \xrightarrow{a} \{1\} \xrightarrow{b} \{2\} \xrightarrow{b} \{3\} \xrightarrow{c} \{4\}: accepted, after 5 unions, one per letter, since each set holds one state.

10. The next set is masked by the positions holding the letter just read; equivalently, every transition into a position carries that position’s letter.

11. At most (57+1)×12=696(57 + 1) \times 12 = 696 (Proposition 22.19).

12. A set of states is the bits of one 128-bit integer, state 0 included. With a vector of 64-bit words as the set, a union costs one OR per word, ⌈(m+1)/64⌉\lceil (m + 1)/64 \rceil in all.

13. Six states: {0}\{0\}; {1}\{1\}, {3}\{3\} and {4}\{4\}, reached by aa, bb and cc; {2}\{2\}, reached from {1}\{1\} by bb; and the sink ∅\emptyset. {2}\{2\} and {3}\{3\} have the transitions of {0}\{0\}.

14. Round 0: {4}\{4\} against the rest. Round 1: {0}\{0\}, {2}\{2\} and {3}\{3\} go to {4}\{4\} on cc, the others do not: three classes. Round 2: {1}\{1\} goes to {2}\{2\} on bb, ∅\emptyset to ∅\emptyset, which are now in different classes: four classes. Round 3 splits nothing. The minimal automaton has 4 states.

15. LL (by ε\varepsilon, bb, abab, …), bLbL (by aa), {ε}\{\varepsilon\} (by cc) and ∅\emptyset (by aaaa, cccc, …): the classes {{0},{2},{3}}\{\{0\}, \{2\}, \{3\}\}, {1}\{1\}, {4}\{4\} and ∅\emptyset.

16. Both denote the words over {a,b}\{a, b\} in which every aa is immediately followed by a bb, then cc. Such a word is a block of bb’s, then blocks starting with abab followed by bb’s, which is b∗(abb∗)∗b^*(abb^*)^*; and every word of b∗(abb∗)∗b^*(abb^*)^* has each aa followed by bb. The checker of Exercise 22.9 confirms it.

17. cc: it is in the first language and lacks the bb before cc in the second. No shorter word differs, since ε\varepsilon, aa and bb are in neither.

18. By Corollary 22.14, patterns with the same language have the same minimal automaton up to the names of the states. Renumbering its states in the order a breadth-first search from the start meets them, letters in a fixed order, makes the transition table and the accepting states a canonical key.

19. 2n2^n: each aa is read by the left or the right branch.

20. Every way reaches the end of the text without a bb and fails; the engine then returns to its last choice and tries the other branch, so it tries all 2n2^n. One more aa doubles the ways, and the measured ratios are close to 2.

21. About 6.6×213≈54 0006.6 \times 2^{13} \approx 54\,000 s, 15 hours.

22. One union for the first letter, from {0}\{0\}, then two for each later one, from {1,2}\{1, 2\}: 2n−12n - 1, as the output shows (39 for 20 letters, 1 999 for 1 000).

23. About 7.3 ns a letter: some 0.3 μ\mus for 40 letters, and 73 ms for ten million.

24. From exponential to linear: on (a∣a)∗b(a \mid a)^*b and ana^n, the backtracking engine’s time doubles with each aa, as measured, reaching 6.6 s at n=27n = 27; the Glushkov matcher makes at most (m+1)n(m + 1)n unions on any pattern of mm positions and any text of nn letters, as proved, here 2n−12n - 1, and answers ten million letters in 73 ms.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো