Consider the following non-deterministic finite automaton (NFA):
If you’ve studied automata theory, you likely learnt that NFAs are equivalent to regular expressions, in the sense that for every NFA there is a regular expression that recognizes the same set of strings as the NFA. So, what is an equivalent regular expression for the NFA above?
In this post, I’d like to share a rather peculiar method to compute the answer to such questions by solving a system of linear equations over regular expressions1. I first learnt this method from Dr. Christian Urban’s course on compilers and formal languages at KCL on exchange.
Let be a regular expression that matches strings that end in state when you run them through the automaton, and similarly let be a regular expression that matches strings ending in state . Although we don’t know what and are yet—if we did, we’d be done!—we can try to write down some constraints that they ought to satisfy. For instance, looking at the NFA diagram, the only way to get to state is if we haven’t seen any characters yet (an empty string), or if we were previously in state and saw the character . In other words, the regular expression should match either the empty string, or followed by the character .
Let’s now agree on two (seemingly unmotivated) conventions for writing regular expressions: instead of using | to denote alternation as in , we will instead write , and additionally we will use to denote the regular expression matching the empty string. We’ll also agree to say that two regular expressions are equal if they match the same set of strings.
Using these strange conventions, we get
which says that matches either the empty string, or followed by the character , as required. Similarly, for , we have the equation
Let’s now throw caution to the wind completely and attempt to solve these equations algebraically, ignoring for the moment that we haven’t the faintest clue what manipulations on these “regular expression equations” are legal or what laws they obey, if any.
By some questionable manipulations on equation (2), we get
Everyone and their mother knows that is just the sum of the infinite geometric series . Alas, we can’t have a regular expression of infinite length, but recalling that means alternation, the expression seems like it matches all the strings that are the character repeated. But that’s just the regular expression ! So:
Now substitute (3) into (1) to get . By applying our questionable geometric series trick again,
Substituting into (3) yields
and since is the only accepting state of the automaton, this regexp should match exactly the strings that are accepted by the NFA. And it truly does! This is the right answer to the original problem (!)
What the hell just happened?
A suspicious algorithm
Summarizing what we just did, here’s our tried-and-true method to convert NFAs to equivalent regular expressions: if the NFA has states , let denote indeterminate regular expressions that match the strings ending in the respective states. Write down equations of the form relating the regular expressions to one another according to the transitions of the NFA, using the notation and as defined before.
Then, simply solve this system of equations in variables by substitution, using the rule when needed (the “geometric series inverse trick”). The answer is given by adding up (i.e., taking an alternation of) the regular expressions corresponding to the accepting states of the NFA.
It turns out that this method does work in general! However, if you’re like me, you are probably scratching your head at this point: clearly these equations have to be interpreted in some kind of underlying algebraic structure on regular expressions. In the remainder of this post, I thus want to answer the following
Question. What is the algebraic structure on regular expressions that allows us to make sense of the equations above? How can we be sure that a unique solution to linear systems formed by the method above exists?
I’ll mostly give intuition, definitions, and statements of results instead of proofs—partly because I’m lazy, and partly because I think the proofs are not really enlightening, but the definitions are.
Regular expressions revisited
To start, we should clarify what we mean by a regular expression: only ‘basic’ features such as sequencing, alternation, and repetition (*) are permitted; fancy stuff like capturing groups, backreferences, and the like are all out of scope. We define regular expressions formally as a recursive datatype.
Definition. A regular expression (regexp) is one of the following:
- , matching the empty string
- a literal symbol , where is a fixed alphabet of valid symbols
- a sequence of smaller two regexps ; often we will omit the symbol and just juxtapose the regexps
- an alternation
- or a repetition .
(There’s in fact one more case, which we’ll get to later—in particular there is also such as a thing as ; see the first paragraph of the next section.)
We declare two regexps to be equal when they match the same set of strings. Formally, we define recursively a function that returns the set of strings that matches: , , etc. (What should the definition for be?2) Two regexps are then equal if .
As you have probably gleaned, the object and the operations , behave somewhat like their real number counterparts. Here’s a non-exhaustive list of nice properties:
- addition is commutative: , since both match either or .
- is the identity with respect to multiplication: , since the left side means “match , then match ”, and matches the empty string.
- multiplication is associative: .
- multiplication distributes over a sum: , since the left side means “match , then either or , which is the same as matching either or ”.
There are some oddities, of course. For instance:
- everything is idempotent with respect to : we have for all regexps .
- we do not have multiplicative inverses in general.3
- multiplication is not commutative: in general , since means to match followed by and the order matters.
With these properties and not-so-nice properties in mind, let’s ask again: what kind of algebraic structure do regular expressions possess?
Rings, semirings, and Kleene algebras
Perhaps you suspect at this point that the set of regular expressions forms a (non-commutative) ring. One obvious issue is that we don’t have an identity for addition; note that is not neutral with respect to addition, since matches both the empty string and , not just . This issue is easily remedied by adding a new object that matches no strings at all to the definition of regular expression. One can check that is indeed neutral with respect to addition and possesses various properties that something called zero ought to.
Unfortunately, even with the regular expressions do not have a ring structure for entirely trivial reasons. Indeed, additive inverses do not exist in general: given a regular expression , what is ? (One might be tempted to define it as the regular expression matching the complement of the language matched by , but unfortunately this does not play well with our existing definitions.4)
Thus is not a ring, since additive inverses do not exist. However, one can actually check that the lack of additive inverses is the only obstruction to being a ring. There is a name for structures that are almost rings but lack only additive inverses: semirings.
Definition (semiring). A semiring satisfies all the ring axioms, except that additive inverses need not exist.
Proposition. The set of regular expressions equipped with alternation as addition and sequencing as multiplication forms a semiring.
But this does not explain everything. In particular, we have not said how the star operation fits into the algebraic structure. If you recall how we “solved” the equation by heuristically writing “” and then using a “geometric series expansion” to get , it seems that the star operation acts as a kind of pseudoinverse.
The notion of a Kleene algebra extends the notion of a semiring to include the operation.
Definition (Kleene algebra). A Kleene algebra is an idempotent semiring with a unary operation such that
- for all , we have and ,
- for all such that , then and ,
where means .
For intuition about the definition of , observe that generally we may interpret in a semiring as a kind of union operation, and so is equivalent to “including” . In the setting of regular expressions, we see that implies that matches all the strings that does (and potentially more).
Proposition. The set of regular expressions is a Kleene algebra.
(Exercise: interpret the two additional axioms concerning in the context of regular expressions. Why do they make sense?)
In fact, regular expressions are the prototypical example of a Kleene algebra; that is, Kleene algebras were introduced to study regular expressions!
In any case, from the defining axioms of a Kleene algebra, we can deduce the following
Lemma (Arden’s lemma). In a Kleene algebra, is the least solution of with respect to .
which (under a mild technical condition) validates our original rule for regular expressions.
Returning to the motivating question of this post—what algebraic structure allows us to make sense of “linear systems in regular expressions”?—one answer is thus that the regular expressions form a Kleene algebra, which is a special case of a semiring. In a Kleene algebra, we may of course solve by substitution and moreover the rule is valid (under a mild technical condition) and known more generally as Arden’s lemma.
Is that the whole story? We haven’t discussed existence and uniqueness of solutions yet, but one can imagine that with the formal definitions above it is not too hard to slog through a proof.
One element of the Kleene algebra viewpoint that I personally find unsatisfying is that we originally “derived” the rule by heuristically manipulating , then multiplying by the inverse of and using a geometric series expansion to get
From the viewpoint of Kleene algebras, even though the end result is justified by Arden’s lemma and can be understood as a kind of pseudoinverse, the intermediate steps are nothing more than a heuristic and cannot be justified formally. One would be excused for dismissing the argument above as nothing more than heuristic thinking that chances upon the right answer—but in fact we can make this argument fully rigorous in the right setting. In particular, by interpreting regular expressions as formal noncommutative power series or formal power series over words, the “inverse” of a regular expression exists in a larger ring. In the last section of this post I will outline this viewpoint and sketch nice proofs of existence and uniqueness of solutions.
Formal power series over words
We build up to the notion of a formal noncommutative power series from more familiar definitions.
Definition (formal power series in one variable). Let be a ring. Then denotes the ring of formal power series in the indeterminate with coefficients in .
Definition (formal power series in multiple commuting variables). Let be a ring. Then denotes the ring of formal power series in commuting indeterminates with coefficients in .
By commuting indeterminates, we mean that we can freely interchange the order in a product: . This allows us to rewrite any product of indeterminates in the canonical form .
If we drop this condition, and instead adjoin non-commutative indeterminates, we naturally obtain the definition of formal noncommutative power series. We indicate noncommutativity by using angled brackets instead of square brackets: that is, in the indeterminates and commute, whereas in they do not.
Let’s think about what the power series living in look like. In particular, what form do individual terms take? In the commutative case each term had the form , which does not distinguish between (say) and . In the noncommutative case these terms are distinct, so we should instead think about terms having the form
where is a finite sequence of 1s and 2s. The term corresponds to , whereas corresponds to , which is a different sequence.
In this way, we see that the power series living in are naturally indexed by words (finite sequences) where each symbol is in , of the form . This leads us to the definition
Definition (formal power series on words). Let be a ring and be a finite alphabet of symbols. Then denotes the ring of formal noncommutative power series .
and as a special case
Definition (formal power series in multiple noncommuting variables). Let be a ring. Then denotes the ring of formal power series .
It took us a bit to arrive at the right definitions, but I hope that the scenic route we took above gives some intuition for why power series on words is a natural non-commutative generalization of regular power series.
Remark. If you really don’t like to reason about power series on words, you can also think of as the set of functions assigning each word an element of . (Why is this equivalent to our definition?)
Regular expressions are just formal series
You may rightfully be wondering what the point of defining power series on words is. Well, let’s write down a regular expression:
Expand this out as . The key insight is that we can think of this as a noncommutative power series in indeterminates , , over , where the coefficient on is and the coefficient on is also !
Are the coefficients always one or zero? Not quite: consider ; it expands to . The coefficient on counts the number of ways for the regular expression to match : see .
What is the analogue of the star operation in ? It seems that we’re a bit stuck now, but let’s recall the heuristic geometric series argument we made earlier: we have , where the last equality is justified since matches any repetition of ’s, which is precisely the definition of .
So perhaps the interpretation of as a formal power series should be , where interprets as a power series in . The beauty is that we can take inverses in the power series ring , as long as the constant term of the power series is a unit!
Theorem. Let be a ring and let . Then exists if and only if the constant term of is a unit in .
Corollary. Let be a ring and suppose that has no constant term. Then exists.
Proof. The constant term of is .
Let’s define the correspondence between regular expressions and formal power series formally now.
Definition (power series interpretation of regexp). Let denote the semiring of regular expressions over . Recall that denotes the ring of formal power series on words over .
Define the power series interpretation of a regular expression , denoted , by
- whenever does not match the empty string.
Here is a partial function .
The condition does not match the empty string in guarantees that has no constant term and hence is invertible. Intuitively, when matches the empty string, we should not expect to have a well-defined power series interpretation since there are infinitely many ways for match the empty string, hence the constant term of must be , which is not in .
In the power series interpretation of regular expressions, the heuristic argument that we originally made has a completely rigorous interpretation in , since subtraction is well-defined and the geometric series expansion is valid whenever has no constant term!
Working in also permits us to prove that the system of linear equations arising from NFA to regexp conversion has a solution. Indeed, take a -free NFA with states , initial states and accepting states . Define a row vector by if and otherwise. Also define a matrix by
For instance, if the alphabet is and the NFA contains transitions and , then .
Each entry of is a nonempty sum of literal symbols (as there are no -transitions), so has no constant term. Writing , the equations produced by our method become the single matrix equation
Theorem (existence and uniqueness). Let and be as above. Then the system has a unique solution , given by
Moreover, the coefficient of a word in is the number of paths in the NFA that start in a state of , read , and end in . In particular, the words with nonzero coefficient in are exactly the words accepted by the NFA.
TODO some subleties (proper regexps, does the answer represent a valid regexp, provenance of these ideas, conclusion)
-
Don’t worry if you haven’t a clue what it means to solve a linear system over regular expressions. I had no idea what was going on under the hood initially either! ↩︎
-
A bit of pondering leads to the definition , where denotes the concatenation of strings and . ↩︎
-
Consider the regexp matching the literal character . Then, if is a multiplicative inverse of , we must have
and in particular this set cannot equal : the displayed set is either empty, or contains one or more strings starting with character . ↩︎
-
Every regular expression is idempotent with respect to , since matching either or is the same as matching ; that is, . If additive inverses exist, adding then gives . But was arbitrary, so this says that the only regular expression is —no good! ↩︎