A Tiny Triple Store

File: TripleStore.lean

A triple is a fact with three parts: subject, predicate, object. “Socrates is a philosopher” is the triple (socrates, is-a, philosopher). This program stores triples in a list and answers queries that contain variables. A query with two patterns that share a variable is a join.

The store holds ten triples:

Subject Predicate Object
socrates is-a philosopher
socrates lives-in athens
plato is-a philosopher
plato lives-in athens
descartes is-a philosopher
descartes lives-in paris
monet is-a painter
monet lives-in paris
voltaire is-a writer
voltaire lives-in paris

RDF names these parts subject, predicate, and object. This program uses strings for all three and one graph. It does not handle blank nodes, datatype literals such as "42"^^xsd:integer, or named graphs.

The Code

 1 -- lean --run TripleStore.lean   (in-memory RDF triple store)
 2 
 3 inductive Term where
 4   | const (name : String)
 5   | var (name : String)
 6 
 7 -- A string literal becomes a Term. A leading ? marks a variable.
 8 instance : Coe String Term where
 9   coe s := if s.startsWith "?" then .var s else .const s
10 
11 abbrev Triple := String × String × String
12 abbrev Pattern := Term × Term × Term
13 abbrev Env := List (String × String)
14 
15 def matchTerm (env : Env) : Term → String → Option Env
16   | .const c, x => if c == x then some env else none
17   | .var v, x =>
18     match env.lookup v with
19     | some bound => if bound == x then some env else none
20     | none => some ((v, x) :: env)
21 
22 def matchTriple (pat : Pattern) (triple : Triple) (env : Env) :
23     Option Env := do
24   let env ← matchTerm env pat.1 triple.1
25   let env ← matchTerm env pat.2.1 triple.2.1
26   matchTerm env pat.2.2 triple.2.2
27 
28 -- Each pattern is joined against the bindings found so far.
29 def query (store : List Triple) (patterns : List Pattern)
30     (envs : List Env := [[]]) : List Env :=
31   match patterns with
32   | [] => envs
33   | pat :: rest =>
34     query store rest (envs.flatMap fun env =>
35       store.filterMap (matchTriple pat · env))
36 
37 def Env.get (env : Env) (v : String) : String :=
38   (env.lookup v).getD "?"
39 
40 def store : List Triple := [
41   ("socrates",  "is-a", "philosopher"),
42   ("socrates",  "lives-in", "athens"),
43   ("plato",     "is-a", "philosopher"),
44   ("plato",     "lives-in", "athens"),
45   ("descartes", "is-a", "philosopher"),
46   ("descartes", "lives-in", "paris"),
47   ("monet",     "is-a", "painter"),
48   ("monet",     "lives-in", "paris"),
49   ("voltaire",  "is-a", "writer"),
50   ("voltaire",  "lives-in", "paris")]
51 
52 def main : IO Unit := do
53   IO.println s!"Knowledge base triples count: {store.length}"
54 
55   IO.println "\nQuery 1: Who is a philosopher?"
56   for b in query store [("?who", "is-a", "philosopher")] do
57     IO.println s!"  who: {b.get "?who"}"
58 
59   IO.println "\nQuery 2: Who lives in Paris AND is a philosopher?"
60   for b in query store [("?who", "lives-in", "paris"),
61                         ("?who", "is-a", "philosopher")] do
62     IO.println s!"  who: {b.get "?who"}"
63 
64   IO.println "\nQuery 3: All people in Paris and their occupations:"
65   for b in query store [("?person", "lives-in", "paris"),
66                         ("?person", "is-a", "?job")] do
67     IO.println s!"  {b.get "?person"} is a {b.get "?job"} in Paris"

How It Works

  • A Term is a constant or a variable. The Common Lisp version tests each symbol at run time to see if its name starts with ?. Here that test runs once, when a string becomes a Term.
  • instance : Coe String Term defines that conversion. Where Lean expects a Term and finds a String, it applies coe. That is why main can write a pattern as three plain strings.
  • An Env is a list of bindings from variable names to values.
  • matchTerm returns Option Env. A constant matches only an equal value. A bound variable matches only the value it is bound to. A free variable matches any value and adds a binding. none means no match.
  • matchTriple is a do block in Option. Each ← passes the bindings to the next step. If any part fails, the result is none.
  • query takes the first pattern and tries it against every triple for every set of bindings found so far. filterMap keeps the some results and drops each none. flatMap joins the lists into one. Then query calls itself on the rest of the patterns.
  • Lean accepts only functions that it can show will stop, unless you mark them partial. query calls itself on a shorter list each time, and Lean finds that proof with no help.

The conversion runs when the program runs, and it decides by the first character. A constant cannot begin with ?, and a misspelled variable name becomes a new variable instead of an error. For a fixed vocabulary, use a Term constructor directly and let the compiler check the name.

query joins patterns left to right. Each pattern filters the current binding list, so a selective pattern first costs less than a broad one. The cost is O(patterns × triples × bindings), because every pattern scans the whole store. In Query 2 either pattern returns three people, so the order does not matter; with a larger store, start with the predicate that has fewer triples. Try this: swap the two patterns in Query 2 and print the binding count after the first pattern.

Lean 4 Notes

What do means for Option. A do block is shorter syntax for nested matches. matchTriple without do looks like this:

1 def matchTriple' (pat : Pattern) (triple : Triple) (env : Env) :
2     Option Env :=
3   match matchTerm env pat.1 triple.1 with
4   | none => none
5   | some env =>
6     match matchTerm env pat.2.1 triple.2.1 with
7     | none => none
8     | some env => matchTerm env pat.2.2 triple.2.2

Each let env ← ... line in the original stands for one match with a none => none case. Each line defines a new env that hides the one before it. Lean allows this, and it is common in do blocks. The shadowing is on purpose: each step must see the bindings from the step before it, and reusing the old name would mislead a reader.

Coercions. Coe String Term is a type class instance like ToString. Lean uses it when the type it expects and the type it finds differ. In main, the list of patterns has the type List Pattern, so Lean expects a Term at each position of each triple and inserts the conversion. The conversion is an ordinary function. It runs when the program runs.

The centered dot. (matchTriple pat · env) is a function of one argument. The dot marks where the argument goes. It is the same as fun triple => matchTriple pat triple env. The parentheses set the limits of the function.

Recursion. query calls itself. Lean must know that a recursive function stops, because you could use a function that loops forever to prove a false statement. Here the match splits patterns into pat :: rest, and the recursive call receives rest. Lean sees that the argument is a part of the original and accepts the definition. When Lean cannot find such an argument, you can prove that the function stops, or mark it partial and lose the ability to prove facts about it.

Default arguments. (envs : List Env := [[]]) gives envs a default: a list that holds one empty set of bindings. The first call in main leaves it out. The recursive call passes it.

Dot calls on an abbreviation. Env is an abbrev for a list of pairs. Env.get is a function in the Env namespace, so b.get "?who" works when b is an Env. The list functions such as lookup still work on it too.

Two kinds of equality test. c == x calls the BEq instance for String and returns a Bool. The code could also use c = x. The tour chapter explains the difference under “Bool and Prop”.

Running It

 1 $ lean --run TripleStore.lean
 2 Knowledge base triples count: 10
 3 
 4 Query 1: Who is a philosopher?
 5   who: socrates
 6   who: plato
 7   who: descartes
 8 
 9 Query 2: Who lives in Paris AND is a philosopher?
10   who: descartes
11 
12 Query 3: All people in Paris and their occupations:
13   descartes is a philosopher in Paris
14   monet is a painter in Paris
15   voltaire is a writer in Paris

query returns environments, not answers. To print one value per person, map Env.get "?who" over the results and call eraseDups; the order follows the store. Query 3 prints each person once because each has one occupation in the store. Try this: add a second occupation for descartes and use eraseDups to remove the duplicate.

Using It

Add your own triples and queries. For a large store, replace the list with a Std.HashMap from predicate to triples so a query does not scan every triple.