iTranslated by AI
Implementing a CCG Parser in Lean 4
In this article, we will implement a simple parser for Combinatory Categorial Grammar (CCG) using Lean 4. We will enumerate derivation trees using a CKY-like chart parsing algorithm and observe them in real-time using #eval.
This article is not about "proving" in Lean, but rather "using Lean as a programming language." However, CCG derivations share some similarities with the nature of proofs, making this an interesting topic with high affinity for Lean.
Target Audience:
- Those interested in functional languages like Lean or Haskell who can read/write them to some extent.
- Those interested in natural language processing, formal grammars, or parser construction.
- Those who have an image of "Lean = proof assistant" but are curious to explore its potential for programming.
What We Will Do in This Article
We will implement a simple CCG parser in Lean 4. We will perform chart parsing using a CKY-like algorithm and enumerate derivation trees.
Key points for programming in Lean are as follows:
- Use
inductiveandinfixto naturally create DSL-like notations and ASTs (Abstract Syntax Trees). - Use
Option,List,HashMap, anddonotation,for,let mutto straightforwardly write search + DP algorithms.
Overview of CCG
CCG is a formal grammar that assigns "Categories" to words and repeatedly synthesizes the categories of words and phrases using "combinatory rules" to see if we ultimately reach category
Categories
Categories are labels representing the syntactic roles of phrases. For those familiar with proof assistants, it is useful to think of them as types or propositions (Lambek calculus).
Categories consist of base categories and functional categories.
- Base categories:
,N ,NP , etc. (intuitively corresponding to nouns, noun phrases, and sentences respectively).S - Functional categories: Two categories joined by operators
and/ .\backslash
Example: ,NP/N ,S\backslash NP , etc.S\backslash NP/NP
Intuitively, functional categories can be understood as follows:
- A phrase with
combines with anNP/N on the right to becomeN (e.g., articles).NP - A phrase with
combines with anS\backslash NP on the left to becomeNP (e.g., intransitive verbs).S
Operators
Combinatory Rules
These are rules for combining multiple (or single) adjacent categories to create new categories.
Representative examples are shown below:
- Forward functional application [>]
X/Y \ \ \ Y \Rightarrow X - Backward functional application [<]
Y \ \ \ X\backslash Y \Rightarrow X - Forward functional composition [>B]
X/Y \ \ \ Y/Z \Rightarrow X/Z - Backward functional composition [<B]
Y\backslash Z \ \ \ X\backslash Y \Rightarrow X\backslash Z - Forward type raising [>T]
X \Rightarrow T/(T\backslash X) - Backward type raising [<T]
X \Rightarrow T\backslash(T/X)
CCG fundamentally builds derivation trees by combining word/phrase categories using these rules to describe the process.
Example of Derivation in CCG
Let's look at the derivation of the sentence "Keats eats apples" in CCG.
First, we assign categories to each word in the sentence:
- "Keats"
\vdash NP - "eats"
\vdash S\backslash NP/NP - "apples"
\vdash NP
We derive the sentence category by combining these using combinatory rules. We can represent the derivation tree using natural deduction notation as follows:

CCG derivation of "Keats eats apples"
First, we combine "eats" (
Note that "Keats eats apples" also allows another derivation:

Alternative CCG derivation of "Keats eats apples"
Here, we raise the category
As shown, the existence of multiple derivations for the same sentence (ambiguity) is a hallmark of CCG.
Implementing a CCG Parser
Now, let's implement the CCG parser.
The complete code can be run in the Lean Playground via the link below. At the bottom of the Playground, you can type:
#eval parse lexicon1 "Keats eats apples"
This will display the list of derivation trees for "Keats eats apples" in the infoview.
Overall Structure
The overall structure of the program is as follows. We have divided the code into section blocks:
- Utility : Tokenization and string helpers
- Category : Definition of category
Cat - Rules : Binary/Unary rules (functional application, composition, type raising)
- Tree : Definition of derivation tree
Tree - Applying : Applying rules to trees to generate new ones
- Parsing : Filling the chart with a CKY-like algorithm
- Example : Execution examples
0. Tips for Programming in Lean
Here are some tips to know when programming in Lean:
-
#evalallows for real-time execution and evaluation.- Use
#eval <term>to display evaluation results. - Customizing the display is possible by making the type an instance of the
ToStringclass.
- Use
- Use
inductive/structure/abbrevfor data definitions.-
inductive: Enumerated types and recursive data (e.g., ASTs). -
structure: Records. -
abbrev: Type aliases.
-
- Search is well-suited for
OptionandList.- Use
nonefor failures. - Use
Listfor multiple candidates. - Combine with
map/flatMap/filterMapto naturally express "enumeration + failure filtering."
- Use
- Use
Id.run do/let mut/forfor procedural style.- Declare mutable variables with
let mut. - Perform repetitions with
for.
- Declare mutable variables with
1. Utility: Tokenization, etc.
abbrev Token := String -- Type for tokens (words)
def String.toTokens (str : String) : List Token :=
str.splitOn.filter (· ≠ "")
Using abbrev to alias Token as String makes it clear in type annotations that the term is a token. Furthermore, calling sentence.toTokens on a String term will be interpreted as String.toTokens sentence (you can call functions using field notation).
2. Category: Defining Categories with inductive
First, we define an enumerated type Dir using inductive to represent the operators / and \ when constructing functional categories.
/-- Direction of functional application -/
inductive Dir : Type
| Fwd -- /
| Bwd -- \
deriving BEq
deriving BEq enables the use of ==. This is necessary for checking whether categories match during combinatorial rule application.
We define the type representing categories as Cat. With inductive, we can define base categories (
/-- Category Cat -/
inductive Cat : Type
| S
| NP
| N
| Fun : Dir → Cat → Cat → Cat -- Functional category x/y or x\y
deriving BEq
For example, Cat.Fun .Bwd .S .NP represents a term of type Cat for
We define infix operators />, \> using infix to align with CCG notation. (The double backslash \\> is used to escape the backslash.)
/-- Notation for functional categories -/
infixl:70 " /> " => Cat.Fun Dir.Fwd -- Notate x/y as x /> y
infixl:70 " \\> " => Cat.Fun Dir.Bwd -- Notate x\y as x \> y
By doing this, you can write categories in a way that looks almost exactly like standard CCG notation, such as .S \> .NP /> .NP.
Making Cat an instance of the ToString type class
By making Dir and Cat instances of the ToString type class, evaluation results in #eval will be displayed nicely in the infoview.
def Dir.toString : Dir → String
| .Fwd => "/"
| .Bwd => "\\"
instance : ToString Dir where
toString := Dir.toString
def Cat.toString : Cat → String
| .S => "S" | .NP => "NP" | .N => "N"
| .Fun d x y =>
match x, y with
| .Fun .., .Fun .. => x.toString ++ d.toString ++ "(" ++ y.toString ++ ")"
| .Fun .., _ => x.toString ++ d.toString ++ y.toString
| _ , .Fun .. => x.toString ++ d.toString ++ "(" ++ y.toString ++ ")"
| _ , _ => x.toString ++ d.toString ++ y.toString
instance : ToString Cat where
toString := Cat.toString
#eval .S /> (.S \> .NP) -- Displays as S/(S\NP)
3. Rules: Representing Rules as "Application Function + Enumerated Type"
Now that we have the categories, let's translate the combinatorial rules into code.
3.1 Combinatorial rule application returns Option Cat
3.1.1 Functional application rule
The function fapp that performs forward functional application [>] returns a term of type Option Cat. It can be written using pattern matching on the structure of the arguments.
/-- Forward functional application
[>] x/y y ➔ x -/
def fapp : Cat → Cat → Option Cat
| .Fun .Fwd x y, y' → if y == y' then some x else none
| _, _ → none
We return none when application fails. This allows us to handle operations like "try all rules and pick only the successful results" simply by using filterMap later.
The function bapp for backward functional application [<] is defined similarly.
3.1.2 Functional composition rule
In addition to the standard composition rule
The function fcompGen for forward (generalized) functional composition [>B] can be defined as follows:
/-- Generalized forward functional composition
[>B] x/y y/$/z ➔ x/$/z -/
def fcompGen : Cat → Cat → Option Cat
| .Fun .Fwd x y, .Fun .Fwd y' z →
if y == y' then
some (x /> z)
else
match fcompGen (x /> y) y' with
| some x' → some (x' /> z)
| none → none
| _, _ → none
The case where y == y' holds is the standard functional composition rule. Deeper compositions are achieved via recursion.
The function bcompGen for backward functional composition [<B] is defined similarly.
3.1.3 Type-raising rule
Unlike the rules above, the type-raising rule is a unary rule that takes a single category and transforms it. Applying type-raising rules without restriction causes the derivation trees to grow infinitely. Here, we limit it to
NP ➔ S/(S\backslash NP) NP ➔ S\backslash (S/NP)
The function fraise that performs forward type-raising [6T] can be defined as follows:
/-- Forward Type rising
[>T] x ➔ t/(t\x) : restricted to x = NP, t = S -/
def fraise (x : Cat := .NP) (t : Cat := .S) : Cat → Option Cat
| .NP → some (t /> (t \> x))
| _ → none
Here, writing (x : Cat := .NP) allows you to set default arguments.
The function braise for backward type-raising [<T] is defined similarly.
Enumerated type for combinatorial rules (linking rule names to implementations)
Combinatorial rules fall into two types:
- Rules taking two categories (binary): Functional application, functional composition
- Rules taking one category (unary): Type-raising
We define enumerated types BinaryRule and UnaryRule to represent the list of application rules, and further define lists binaryRules and unaryRules.
inductive BinaryRule : Type
| Fa | Ba | Fc | Bc -- [>], [<], [>B], [<B]
inductive UnaryRule : Type
| Ft | Bt -- [>T], [<T]
def binaryRules : List BinaryRule := [.Fa, .Ba, .Fc, .Bc]
def unaryRules : List UnaryRule := [.Ft, .Bt]
We map the elements of the enumerated types to the rule implementations defined earlier:
def BinaryRule.applyBinary : BinaryRule → Cat → Cat → Option Cat
| .Fa → fapp
| .Ba → bapp
| .Fc → fcompGen
| .Bc → bcompGen
def UnaryRule.applyUnary : UnaryRule → Cat → Option Cat
| .Ft → fraise
| .Bt → braise
By doing this, operations like "try all rules" can be written naturally using map or filterMap.
4. Tree: Defining derivation trees with inductive
A derivation tree Tree can be defined using inductive as an inductive type.
inductive Tree : Type
| leaf (tok : Token) (c : Cat) -- Category of a word
| binary (r : BinaryRule) (c : Cat) (lt rt : Tree) -- Application of binary rule
| unary (r : UnaryRule) (c : Cat) (t : Tree) -- Application of unary rule (type-raising)
We provide Tree.cat so that we can easily extract the category of a tree.
def Tree.cat : Tree → Cat
| .leaf _ c → c
| .binary _ c _ _ → c
| .unary _ c _ → c
Although we omit the details here, Tree should also be made an instance of the ToString type class so that derivation trees are displayed clearly.
5. Applying: Writing rule application as enumeration
The operation "try all binary rules on two categories and pick only the successful results" can be written using filterMap.
def tryBinaryRules (lc rc : Cat) : List (BinaryRule × Cat) :=
binaryRules.filterMap fun r ↦
(r.applyBinary lc rc).map (r, ·)
combineTree wraps the result in Tree.binary to create a new derivation tree.
def combineTree (lt rt : Tree) : List Tree :=
let applied := tryBinaryRules lt.cat rt.cat
applied.map fun (r, c) ↦ .binary r c lt rt
Similarly, raiseTree, which applies unary rules, can be defined as follows:
def tryUnaryRules (c : Cat) : List (UnaryRule × Cat) :=
unaryRules.filterMap fun r ↦
(r.applyUnary c).map (r, ·)
def raiseTree (t : Tree) : List Tree :=
let applied := tryUnaryRules t.cat
applied.map fun (r, c) ↦ .unary r c t
6. Parsing: Performing CKY-like DP with HashMap charts
This is the main part of the parser implementation. We will perform analysis using Dynamic Programming (DP) based on the CKY (Cocke-Kasami-Younger) algorithm used in phrase structure parsing.
Let's explain the algorithm. Consider the token sequence toks = ["Keats", "eats", "an", "apples"] (token length len = 4). We consider a chart for this token sequence as shown in the figure.

Chart for "Keats eats an apple"
The chart has cells for each "interval of length span starting at position i (0-index)", and the cell (span, i) holds a list of derivation trees covering the part from token i to i+span-1 (length span).
Derivation trees for each cell can be constructed using derivation trees of the parts below the pyramid with that cell as the vertex. For example, the derivation tree for the cell (3, 0) "Keats eats an" can be created by combining the derivation tree of the cell (2, 0) "Keats eats" and the derivation tree of the cell (1, 2) "an" using binary rules (there is also a combination of the cell (1, 0) "Keats" and the cell (2, 1) "eats an"). The derivation tree for the cell (2, 0) can also be created by combining the cells (1, 0) and (1, 1) below it.
Therefore, by creating derivation trees starting from the bottom layer span = 1 cells and sequentially constructing derivation trees for cells in the upper layers, we can finally obtain the list of derivation trees for the top cell (len, 0), i.e., the entire token sequence.
6.1 Defining Category Dictionary Lexicon and Chart with HashMap
We define the category dictionary and chart using HashMap. Therefore, we import Std.Data.HashMap at the beginning of the file.
import Std.Data.HashMap
The category dictionary type Lexicon is defined as a HashMap with tokens as keys and lists of categories as values.
/-- Category dictionary type -/
abbrev Lexicon := Std.HashMap Token (List Cat)
def Lexicon.getCats (lex : Lexicon) (t : Token) : List Cat :=
lex.getD t []
We also defined getCats to obtain the list of categories for a token. getD returns a default value if the key does not exist. Thus, unknown words not in the dictionary return [].
Concrete category dictionaries will be exemplified in 7. Example.
The chart type Chart is a HashMap with (span, i) as key and the list of derivation trees for that cell as value.
/-- Chart type
key = (span, i), value = "List of derivation trees for the part of span tokens from i"
-/
abbrev Chart := Std.HashMap (Nat × Nat) (List Tree) -- key : (span, i)
def Chart.getTrees (chart : Chart) (span_i : Nat × Nat) : List Tree :=
chart.getD span_i []
Note that the condition for being a key in a HashMap is that it must be an instance of the BEq and Hashable type classes. String, Nat, and Nat × Nat already have these instances, so they can be used as is.
6.2 fillChart: Writing DP with Id.run do + let mut
We will fill the chart with a CKY-style algorithm. Roughly, the steps are as follows:
-
span = 1:- Create leaves from the category dictionary
lexfor each tokent - Add trees with unary rules applied to the leaves
- Create leaves from the category dictionary
-
span ≥ 2:- Move the split point
kto create trees withcombineTree - Add trees with unary rules applied there
- Move the split point
In Lean, you can write programs in a local procedural style using do notation.
/-- ## CKY Parsing -/
def fillChart (lex : Lexicon) (toks : List Token) : Chart := Id.run do
let len := toks.length
let mut chart : Chart := {}
-- Create leaf nodes + Apply type-raising (span = 1)
let span : Nat := 1
for (t, i) in toks.zipIdx do
let leaves : List Tree := (lex.getCats t).map (.leaf t ·)
let raised : List Tree := leaves.flatMap (raiseTree ·) -- Apply type-raising
chart := chart.insert (span, i) (leaves ++ raised) -- Update chart (add cell)
-- Combine derivation trees bottom-up + Apply type-raising (span ≥ 2)
for span in 2...(len + 1) do
for i in 0...(len - span + 1) do
let mut trees : List Tree := []
for k in 1...span do
let lts := chart.getTrees (k, i)
let rts := chart.getTrees (span - k, i + k)
trees := trees ++
lts.flatMap fun lt ↦ rts.flatMap fun rt ↦ combineTree lt rt
let raised : List Tree := trees.flatMap (raiseTree ·) -- Apply type-raising
chart := chart.insert (span, i) (trees ++ raised) -- Update chart
return chart
It is helpful to read the code focusing on the following points:
-
Id.run do:
Returns the result of thedoblock as a value (here, it returnschart : Chart) -
let mut chart := {}..chart := chart.insert..:
Inside thedoblock, you can declare/initialize a mutable variable and update its value. (Behind the scenes, it is handled nicely with the state monad transformerStateT) -
for span in 2...(len+1) do,for i in 0...(len-span+1) do:
Nested loop to traverse chart cells from bottom and left -
lts.flatMap fun lt ↦ rts.flatMap fun rt ↦ combineTree lt rt:
Can cleanly write all combinations (exploration) of the left and right cells
6.3 parse function
The CCG parser parseCCG returns the list of derivation trees for the token sequence by creating a chart with fillChart and returning its top cell.
def parseCCG (lex : Lexicon) (toks : List Token) : List Tree :=
let chart := fillChart lex toks
let len := toks.length
chart.getTrees (len, 0) -- Chart top
def parse (lex : Lexicon) (sentence : String): List Tree :=
let toks : List Token := sentence.toTokens
parseCCG lex toks
When you pass (a category dictionary and) a string to parse, it automatically splits it into tokens, parses it, and gives you the results.
7. Example: Execution with #eval
Example 1) Keats eats apples
Now that we have implemented the parser (parse), let's try running it. First, define the category dictionary as follows:
def lexicon1 : Lexicon := {
("Keats", [.NP]),
("eats", [.S \> .NP /> .NP]),
("cooks", [.S \> .NP /> .NP]),
("an", [.NP /> .N]),
("apple", [.N]),
("apples", [.NP])}
Passing the category dictionary and a sentence (string) to parse will yield a list of derivation trees. Let's evaluate it with #eval. (I re-insert the link to the Lean Playground)
#eval parse lexicon1 "Keats eats apples"
The following 4 types of derivation trees are obtained (displayed in the infoview).
Derivation results of "Keats eats apples"
[
S [<]
├NP "Keats"
├S\NP [>]
│├S\NP/NP "eats"
│├NP "apples",
S [>]
├S/(S\NP) [>T]
│├NP "Keats"
├S\NP [>]
│├S\NP/NP "eats"
│├NP "apples",
S [>]
├S/NP [>B]
│├S/(S\NP) [>T]
││├NP "Keats"
│├S\NP/NP "eats"
├NP "apples",
S [<]
├S/NP [>B]
│├S/(S\NP) [>T]
││├NP "Keats"
│├S\NP/NP "eats"
├S\(S/NP) [<T]
│├NP "apples"]
The notation of the derivation trees is different from that shown in the CCG explanation, but the correspondence of the tree structures should be discernible.
#eval parse lexicon2 "Keats cooks an apple"
It is also a good idea to try things like this.
Example 2) I think that that that that that boy wrote is wrong
Even for this famous sentence, derivation can be performed by reflecting the polysemy of "that" in its category. (However, the number of candidate derivation trees will balloon.)
def lexicon2 : Lexicon := {
("I", [.S /> (.S \> .NP)]),
("think", [.S \> .NP /> .S,]),
("that", [.S /> .S, .NP /> .N, .N, .N \> .N /> (.S /> .NP)]),
("boy", [.N]),
("wrote", [.S \> .NP /> .NP]),
("is", [.S \> .NP /> (.S \> .NP)]),
("wrong", [.S \> .NP])}
#eval parse lexicon2 "I think that that that that that boy wrote is wrong"
Development: Semantic Composition in CCG
Up to this point, we have worked on the implementation of a parser that combines and synthesizes CCG categories. Actually, the most interesting part of CCG is that it also performs the synthesis of "meaning" in addition to categories.
Let's look at an example. For each word in "Keats eats apples", we associate its category with a lambda expression representing its meaning. (In the context of type theory, lambda expressions can be viewed as terms or proofs for categories (types or propositions).)
- "Keats" ⊢
NP : keats - "eats" ⊢
S\backslash NP/NP : \lambda y. \lambda x. eat(x, y) - "apples" ⊢
NP : apples
Combination rules also perform the synthesis of meaning in addition to the synthesis of categories. For example, functional application rules are defined as follows:
- Forward functional application [>]
X/Y : f \ \ \ Y : a \Rightarrow X : f a - Backward functional application [<]
Y : a \ \ \ X\backslash Y : f \Rightarrow X : f a
By performing the derivation of categories via combination rules, the synthesis of meaning is also performed automatically as shown in the figure, and finally, a lambda expression (logical formula)
Meaning composition for "Keats eats apples" in CCG
Since Lean is a functional programming language, lambda expressions are its forte, so it is quite possible to extend the parser to also perform CCG meaning composition (though I won't say it's easy).
Conclusion
In this article, using the implementation of a simple CCG parser as a theme, we explained a series of programming experiences in Lean:
- Creating a DSL with
inductive/infix - Building exploration with
Option/List - Implementing dictionaries and charts with
HashMap - Writing DP with
Id.run do/for/let mut - Experimenting with
#eval
Lean is easy to write by combining its style as a functional programming language with a procedural style using do notation and for, making it a language that is easy to use for building parsers.
Furthermore, it becomes possible to use Lean as a proof assistant to prove whether the implemented parser is correct.
Please try your hand at programming in Lean.
Recommended References
- Daisuke Bekki, "Formal Theory of Japanese Grammar: Inflection System, Syntactic Structure, and Semantic Composition", Kuroshio Publishers (2010)
Constructs Japanese CCG including semantics. There are many difficult parts, but it is very interesting to feel the spirit of wanting to analyze Japanese thoroughly with CCG. - Masayuki Tsuruoka (Author), Yusuke Miyao (Author), Manabu Okumura (Supervisor), "Syntactic Analysis (Natural Language Processing Series)", Corona Publishing (2017)
As the title suggests, it is a textbook on syntactic analysis. Various algorithms including CKY are explained. There is also a description of CCG.
Discussion
#eval について
どちらかというとevalに使われるのはReprです。ToString とは用途が異なります。