Search

Search papers and lessons

Formal Language

Level 2 · 10 min read

A formal language is a set of strings over a fixed alphabet, where an exact rule decides which strings belong to it.

On this page

  • Colour = topic mix
  • Programming languages
  • Discrete math
  • ReadReady to readNot yet

TL;DR

A formal language is a set of strings made from a fixed list of symbols, such as the letters 0 and 1. Its defining feature is that an exact rule decides, for any string, whether it belongs to the set or not. This gives programs and tools a precise meaning for words like "valid identifier" or "well-formed number". The idea is the base of compilers, search tools and input checking.

Builds on: Set Operations · Leads to: Context-Free Grammar, State Machine

Where it's used

Programming language lexers. Before a compiler understands a program, a lexer splits the source text into tokens such as names, numbers and operators. Each token type is a small formal language. A name, for example, is defined as a letter followed by any number of letters, digits or underscores. The lexer uses the rule to decide whether a run of characters is a name or an error.

Search tools such as grep. When you search a log file with a pattern like ERROR [0-9]+, the tool checks each line against a rule. The pattern describes a formal language, and the tool reports the lines whose text belongs to it. Patterns of this kind are the everyday face of formal languages.

Input checking and protocols. A web form that accepts only a five-digit postal code, or a network message that must start with a fixed header, is checking that its input belongs to a language. A server that rejects a malformed request has answered the question "is this string in my language?" with no.

How it works

Take a tiny instance. The alphabet is {0,1}\{0, 1\}. The language LL is the set of strings that contain an even number of 1s. We will test the string 10011001.

  1. Start the count. Set a counter to 0. Nothing has been read yet, so the string is still undecided. Check: the counter is even, as it would be for an empty string.
  2. Read the first symbol, 1. It is a 1, so the counter goes up to 1. Check: one 1 so far, which is odd.
  3. Read the second symbol, 0. It is not a 1, so the counter stays at 1. Check: the number of 1s has not changed.
  4. Read the third symbol, 0. Again not a 1, so the counter stays at 1. Check: still one 1.
  5. Read the fourth symbol, 1. It is a 1, so the counter goes up to 2. Check: two 1s, which is even.
  6. Decide at the end. The string has no symbols left. The counter is even, so 10011001 belongs to LL.

The rule is what defines the language. The set of members is usually infinite and is never written out in full. A language is fixed by a rule (or a machine that applies the rule), and the rule answers yes or no for every string.

flowchart LR
  A["string w over the alphabet"] --> B{"rule: even number of 1s?"}
  B -->|yes| C["w is in L"]
  B -->|no| D["w is not in L"]

The math

Definition: Formal language
Let Σ\Sigma be a finite, nonempty set of symbols, called the alphabet. A language over Σ\Sigma is any subset L⊆Σ∗L \subseteq \Sigma^*.

Step 1 in symbols: strings and the alphabet

A string over Σ\Sigma is a finite sequence w=w1w2⋯wnw = w_1 w_2 \cdots w_n in which every wiw_i belongs to Σ\Sigma. Its length is ∣w∣=n|w| = n, the number of symbols. The empty string ε\varepsilon is the string with no symbols, so ∣ε∣=0|\varepsilon| = 0.

For each length nn, the strings of length nn form the set Σn\Sigma^n. Because each of the nn positions can hold any of the ∣Σ∣|\Sigma| symbols, ∣Σn∣=∣Σ∣n|\Sigma^n| = |\Sigma|^n. For Σ={0,1}\Sigma = \{0, 1\} and n=4n = 4, this gives 24=162^4 = 16 strings.

The set of all strings over Σ\Sigma is Σ∗=Σ0∪Σ1∪Σ2∪⋯\Sigma^* = \Sigma^0 \cup \Sigma^1 \cup \Sigma^2 \cup \cdots. It contains ε\varepsilon and is infinite whenever Σ\Sigma is nonempty.

Step 2 in symbols: the rule as a property

A language is described by a property PP that a string may or may not have:

L={ w∈Σ∗:P(w) }L = \{\, w \in \Sigma^* : P(w) \,\}

In the example, P(w)P(w) is "the number of 1s in ww is even". Membership is a yes-or-no question, a Function from strings to yes or no: w∈Lw \in L exactly when P(w)P(w) is true.

Step 3 in symbols: combining strings

For strings uu and vv, the concatenation uvuv is the string that writes uu and then vv. Its length is ∣uv∣=∣u∣+∣v∣|uv| = |u| + |v|. Concatenation of languages is L1L2={ uv:u∈L1, v∈L2 }L_1 L_2 = \{\, uv : u \in L_1,\ v \in L_2 \,\}. Union and intersection of languages are the ordinary set operations, because a language is a set.

Step 4 in symbols: the answer

Let c(w)c(w) be the number of 1s in ww. The property in the example is c(w) mod 2=0c(w) \bmod 2 = 0, read "the remainder when c(w)c(w) is divided by 2 is 0". For w=1001w = 1001, c(w)=2c(w) = 2, and the remainder of 2 divided by 2 is 0, so 1001∈L1001 \in L. The state machine in the state-machine view computes the same answer one symbol at a time, keeping only the remainder so far.

Worked examples

Example
Example 1: all strings of length 2 over {a, b}
  1. The alphabet is Σ={a,b}\Sigma = \{a, b\}, so ∣Σ∣=2|\Sigma| = 2.
  2. Strings of length exactly 2 are the set Σ2={aa,ab,ba,bb}\Sigma^2 = \{aa, ab, ba, bb\}, which has 22=42^2 = 4 members.
  3. Define L=Σ2L = \Sigma^2. Test abab: it has length 2 and uses only aa and bb, so ab∈Lab \in L.
  4. Test aa: its length is 1, so a∉La \notin L.
  5. Test ε\varepsilon: its length is 0, so ε∉L\varepsilon \notin L.

Interpretation: LL is a finite language. Its rule ("length exactly 2") is simpler than listing its members, but both describe the same set.

Example
Example 2: an even number of 1s
  1. Use the alphabet {0,1}\{0, 1\} and the language LL from How it works.
  2. Test 10111011. Its 1s are in positions 1, 3 and 4, so there are three of them. Three is odd, so 1011∉L1011 \notin L.
  3. Test 10011001 again. It has two 1s, so 1001∈L1001 \in L.
  4. Test ε\varepsilon. It has zero 1s, and zero is even, so ε∈L\varepsilon \in L.
  5. Split 10111011 into 1010 and 1111. Each piece is a string, and concatenating them gives 10⋅11=101110 \cdot 11 = 1011.
  6. Count the 1s in the two pieces: 1010 has one 1 and 1111 has two, for three in total. This matches the count of three from step 2, so the count is preserved by concatenation.

Interpretation: a rule about a count can be checked symbol by symbol, and the answer depends only on the count, not on the order of the symbols.

Example
Example 3: identifiers in a programming language

Take the alphabet of letters a to z, uppercase A to Z, digits 0 to 9, and the underscore. This has 63 symbols, and the ASCII set has 128 characters in total. An identifier is a string that starts with a letter or underscore and continues with letters, digits or underscores.

  1. Test x1x_1. It starts with the letter xx, and the rest is 1_1, which uses only allowed symbols. So x1x_1 is an identifier.
  2. Test __init\_\_init. It starts with an underscore and the rest uses only letters, so it is an identifier.
  3. Test 9lives9lives. It starts with the digit 9, which the rule forbids as a first symbol. So 9lives9lives is not an identifier, and a lexer reports an error.
  4. Test run−fastrun-fast. The hyphen is not in the alphabet of allowed continuation symbols, so the string is not an identifier.

Try it: Is a9_ba9\_b an identifier? Answer: Yes. It starts with the letter aa, and the remaining symbols 99, _\_ and bb are all digits, underscores or letters.

Common mistakes and tradeoffs

It is tempting to think a string is just a set of its symbols. In fact order matters, because abab and baba are different strings, even though they use the same symbols. Strings are sequences, and that is why the concatenation step in the math is not commutative.

It is tempting to think the empty string ε\varepsilon and the empty language ∅\varnothing are the same thing. In fact ε\varepsilon is a string of length 0, while ∅\varnothing is a language with no strings at all. The language {ε}\{\varepsilon\} contains exactly one string, and ∅\varnothing contains none.

It is tempting to think a language must be infinite or hard to describe. In fact finite languages are also languages, and the simplest one, ∅\varnothing, has no members. A finite language can be listed, which is often the clearest choice for a short set of keywords.

When to use the formal-language view: when you need an exact yes-or-no answer for every string, as in a compiler or a validator. When not to: natural human language is too irregular for a clean rule, so exact formal languages are used for programming and protocols, not for everyday speech. Listing the members works for finite sets, and a grammar or a machine works for infinite ones.

History

In the 1950s, researchers working on computing and on linguistics asked how to describe the set of "correct" sentences of a language. Noam Chomsky's 1956 paper defined classes of formal languages by the kind of rule that generates them, and this grew into the Chomsky hierarchy. Stephen Kleene's work on regular events, in the same decade, gave the star notation Σ∗\Sigma^* used here. Around 1960, the report on the ALGOL 60 programming language used a notation for grammar rules to define a programming language precisely, and the idea caught on because it let compilers check programs mechanically.

Recap

  • An alphabet is a finite nonempty set of symbols, and a string is a finite sequence of them.
  • Σ∗\Sigma^* is the set of all strings, including the empty string ε\varepsilon.
  • A formal language is any subset of Σ∗\Sigma^*, and a rule (a property of strings) defines it.
  • Membership is a yes-or-no question about one string, and a machine can answer it one symbol at a time.
  • Next, read Context-Free Grammar to see how rules that generate strings define larger languages, and State Machine to see how a machine decides membership.

Check yourself

QuestionWhat is the difference between the empty string and the empty language?Show answer
The empty string ε\varepsilon is a string of length 0, so it is one member of Σ∗\Sigma^*. The empty language ∅\varnothing is a language with no members at all. The language {ε}\{\varepsilon\} has exactly one member, and it is not the same as ∅\varnothing.
QuestionOver the alphabet {a,b,c}\{a, b, c\}, how many strings have length exactly 3?Show answer
Each of the 3 positions can hold any of the 3 symbols, so there are 33=273^3 = 27 strings. The count of length-nn strings is ∣Σ∣n|\Sigma|^n, as in the math section.
QuestionWhy can a rule about the number of 1s be checked one symbol at a time, while the order of the 1s and 0s does not matter for the answer?Show answer
The rule depends only on the count of 1s. A counter can be updated as each symbol is read, and it never needs to know which positions held the 1s. The rule is order-independent, but the strings themselves are still sequences, so 10011001 and 00110011 are different strings with the same answer.
QuestionA lexer treats `2fast` as an error. Using the identifier rule from Example 3, explain why this is correct, and say what a valid name would need to change.Show answer
The identifier rule requires the first symbol to be a letter or underscore, and 22 is a digit, so 2fast2fast is not in the identifier language. To make it valid, the name would have to start with a letter or underscore, for example fast2fast2 or _2fast\_2fast.

Sources