iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🧩

Implementing a CCG Parser in Lean 4

に公開
2026/02/06
1件

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:

  1. Use inductive and infix to naturally create DSL-like notations and ASTs (Abstract Syntax Trees).
  2. Use Option, List, HashMap, and do notation, for, let mut to 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 S (sentence).

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, S, etc. (intuitively corresponding to nouns, noun phrases, and sentences respectively).
  • Functional categories: Two categories joined by operators / and \backslash.
    Example: NP/N, S\backslash NP, S\backslash NP/NP, etc.

Intuitively, functional categories can be understood as follows:

  • A phrase with NP/N combines with an N on the right to become NP (e.g., articles).
  • A phrase with S\backslash NP combines with an NP on the left to become S (e.g., intransitive verbs).

Operators / and \backslash are left-associative; for example, S\backslash NP/NP is read as (S\backslash NP)/NP.

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:

"Keats eats apples" derivation tree
CCG derivation of "Keats eats apples"

First, we combine "eats" (S\backslash NP/NP) and "apples" (NP) using forward functional application [>] to create S\backslash NP, then combine it with "Keats" (NP) using backward functional application [<] to finally obtain S.
Note that "Keats eats apples" also allows another derivation:

"Keats eats apples" alternative derivation tree
Alternative CCG derivation of "Keats eats apples"

Here, we raise the category NP of "Keats" to S/(S\backslash NP) using type raising [>T], then perform function composition [>B] and functional application [>] to obtain S.

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:

  1. Utility : Tokenization and string helpers
  2. Category : Definition of category Cat
  3. Rules : Binary/Unary rules (functional application, composition, type raising)
  4. Tree : Definition of derivation tree Tree
  5. Applying : Applying rules to trees to generate new ones
  6. Parsing : Filling the chart with a CKY-like algorithm
  7. Example : Execution examples

0. Tips for Programming in Lean

Here are some tips to know when programming in Lean:

  1. #eval allows 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 ToString class.
  2. Use inductive / structure / abbrev for data definitions.
    • inductive: Enumerated types and recursive data (e.g., ASTs).
    • structure: Records.
    • abbrev: Type aliases.
  3. Search is well-suited for Option and List.
    • Use none for failures.
    • Use List for multiple candidates.
    • Combine with map / flatMap / filterMap to naturally express "enumeration + failure filtering."
  4. Use Id.run do / let mut / for for procedural style.
    • Declare mutable variables with let mut.
    • Perform repetitions with for.

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 (S, NP, N) enumeratively and functional categories recursively.

/-- 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 S\backslash NP.

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 X/Y \ Y/Z ➔ X/Z, we implement a generalized functional composition rule that also covers deeper compositions like X/Y \ Y/W/Z ➔ X/W/Z.
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 only, in the forms:

  • 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.

"Keats eats an apple" chart
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:

  1. span = 1:
    • Create leaves from the category dictionary lex for each token t
    • Add trees with unary rules applied to the leaves
  2. span ≥ 2:
    • Move the split point k to create trees with combineTree
    • Add trees with unary rules applied there

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 the do block as a value (here, it returns chart : Chart)
  • let mut chart := {} .. chart := chart.insert..:
    Inside the do block, you can declare/initialize a mutable variable and update its value. (Behind the scenes, it is handled nicely with the state monad transformer StateT)
  • 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) eat(keats, apples) representing the meaning of the entire sentence can be obtained (β-reduced as appropriate).
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.

Discussion