A Simple In-Memory RDF Store and Query Language in Gerbil Scheme
Introduction to RDF and the Goal of This Chapter
As we saw in an earlier chapter, the Resource Description Framework (RDF) is a W3C standard for representing knowledge as a graph of statements. Every statement is a triple: a subject, a predicate, and an object. Taken together, a collection of triples forms a directed, labeled graph that can represent almost any kind of structured knowledge, from social networks and bibliographic data to scientific datasets and knowledge bases.
SPARQL is the standard query language for RDF graphs. It lets you express patterns of triples you are looking for, binding variables to the parts of the graph that match. A full SPARQL 1.1 engine is a substantial piece of software, but the core idea (matching a set of triple patterns against a store and collecting the variable bindings) is straightforward to implement from scratch.
This chapter walks through an implementation in RDF.ss, found in the directory gerbil_scheme_book/source_code/RDF_datastore, that is a self-contained Gerbil Scheme file that implements both pieces: a mutable in-memory triple store and a small SPARQL evaluator that handles the most commonly used fragment of the language. The goal is not to replace a production-grade triplestore, but to show how cleanly the underlying ideas map onto idiomatic Scheme code.
We will list the complete implementation later; first we discuss our approach to writing a simple RDF data store with a simple but usable subset SPARQL query language.
Data Model: Triples and the Store
The fundamental unit of RDF is the triple (subject predicate object). In
RDF.ss each triple is represented as a plain three-element Scheme list.
This is intentionally simple: lists are transparent, easy to inspect in the
REPL, and require no additional data-structure support from the runtime.
The store itself is a mutable wrapper around a list of those triples. It is
created with make-store and manipulated through two mutating operations:
add-triple and remove-triple. Both operations return the store itself,
which makes it natural to chain a series of add-triple calls when loading
data. store-triples extracts the raw list for inspection or iteration.
Choosing a mutable design keeps the loading code simple and mirrors what a developer would expect from a database: you add facts, you remove facts, and the store reflects the current state of knowledge. A persistent (immutable) variant would be straightforward to build on top of the same ideas by threading the store through every call rather than mutating it in place.
A small helper, print-all-triples, dumps the entire store to standard
output. It is useful during development and debugging and is used in the
demo at the bottom of RDF.ss to show the loaded data before any queries
are run.
Parsing SPARQL Queries
Before any matching can happen, the textual query string must be turned into a structured representation the evaluator can work with. RDF.ss handles this in two stages: tokenization and parsing.
Tokenization
The tokenizer in RDF.ss walks the query string one character at a time,
accumulating characters into a buffer and flushing the buffer into a token
whenever it encounters whitespace or one of the SPARQL punctuation characters
{, }, ., ,, ;, (, and ). Each punctuation character also
becomes its own single-character token. The result is a flat list of strings
that the parser can consume one element at a time without worrying about
character-level details.
Apart from the single helper char-whitespace? (which checks for space, tab,
newline, and carriage return), the tokenizer depends on nothing but basic
Scheme list and string operations.
Parsing
The parser implemented in parse-sparql consumes the token list produced by
the tokenizer and returns two values via let-values:
- vars: the list of variable names the query projects, or the single wildcard token
"*"when the query usesSELECT *. - patterns: the list of triple patterns from the
WHEREclause, each represented as a three-element list of strings in the same(s p o)shape as stored triples.
The parser first scans forward to the SELECT keyword, then reads variable
tokens (anything beginning with ?) or the * token until it hits a
non-variable. It then scans to the opening { of the WHERE block and
reads groups of three tokens as triple patterns, discarding optional trailing
. separators and stopping at the closing }.
The parser treats tokens as plain strings: resources, literals, and variables
are all strings, while SPARQL keywords (SELECT, WHERE) are matched
case-insensitively. The tokenizer preserves <...> IRIs (such as
<http://example.org/Alice>) and "..." string literals atomically without
splitting on internal punctuation or spaces. This avoids the need for a
separate IR type hierarchy and keeps the code focused on structural logic.
The following architecture diagram illustrates the structure of the in-memory RDF store, showing the data flow from triple storage through SPARQL query tokenization, parsing, pattern matching, and result projection.

Query Evaluation: Pattern Matching and Joining
The evaluator in RDF.ss works in terms of environments, association
lists that map variable name strings to the string values they have been
bound to. An empty environment '() represents “no bindings yet” and is
the starting point for every query.
Matching a Single Pattern against a Triple
match-pattern tries to unify one triple pattern with one stored triple
given an existing environment. For each of the three positions (subject,
predicate, object) it applies one of two rules:
If the pattern element is a variable (detected by
var?, which checks for a leading?), look the variable up in the current environment. If it is already bound, check that the bound value equals the triple’s value at that position; a mismatch means the pattern fails. If it is unbound, extend the environment with the new binding.If the pattern element is a concrete value (a resource or literal), check that it is exactly equal to the triple’s value at that position. If not, the match fails.
The three checks are sequenced so that a failure at any position short-circuits the
rest: e1 is the environment after checking the subject, e2 after the
predicate (or #f if e1 failed), and e3 after the object. The final
value e3 is either a valid extended environment or #f.
The helper env-extend encapsulates the extend-or-check logic. It uses
assoc to look up the variable; if a binding exists and matches, it returns
the unchanged environment; if a binding exists but conflicts, it returns #f;
otherwise it prepends a new (var . val) pair.
Joining Multiple Patterns
A SPARQL WHERE clause typically contains more than one triple pattern, and
the results must satisfy all of them simultaneously. join-patterns
implements this as a recursive nested-loop join:
- Start with a list of one empty environment.
- For the first pattern, try matching it against every triple in the store. Collect all the environments that survive (i.e.,
match-patternreturned non-#f). - Recurse on the remaining patterns, passing those surviving environments as the new starting set.
- When no patterns remain, whatever environments are left are the solutions.
This is equivalent to computing a relational cross-product filtered by the match conditions: a join. Because each pattern can bind new variables, the common variables between two patterns act as join keys automatically, without any explicit join condition.
The algorithm is correct for any number of patterns. In the worst case, its time complexity is $O(T^P)$ where $T$ is the number of triples and $P$ is the number of patterns, though selective patterns prune intermediate environments early. For a small in-memory store that is entirely acceptable.
Projecting Results
Once join-patterns returns the list of surviving environments, sparql-select
projects each one down to the variables named in the SELECT clause. For
each result environment, it calls project-env, which walks the selected
variable list and pulls out the corresponding value from the environment via
env-lookup.
When SELECT * is used, no projection is applied. The full environment is
returned as-is, which contains all variables that were bound during matching.
Gerbil RDF Implementation
1 ;;; RDF.ss ── simple in-memory RDF data store with a toy SPARQL subset
2 ;;;
3 ;;; Supports:
4 ;;; make-store – create an empty triple store
5 ;;; add-triple – add an (s p o) triple (set-like, no duplicates)
6 ;;; remove-triple – remove the first matching (s p o) triple
7 ;;; store-triples – retrieve all triples from a store
8 ;;; sparql-select – run a SELECT query (variables + WHERE patterns)
9 ;;; print-all-triples – display all triples for debugging
10
11 (export make-store add-triple remove-triple store-triples
12 sparql-select print-all-triples main)
13 (import :std/srfi/13 :gerbil/gambit)
14
15 ;;;; ──────────────────────────────────────────────────────────────────
16 ;;;; 1. Data model
17 ;;;; ──────────────────────────────────────────────────────────────────
18
19 ;; A store is just a cons-cell box wrapping a list of triples.
20 ;; Each triple is a 3-element list: (subject predicate object).
21
22 (define (make-store) (cons 'rdf-store '()))
23
24 (define (store-triples st) (cdr st))
25
26 (define (add-triple st s p o)
27 ;; Add the triple (s p o) to store ST if not already present; returns ST for chaining.
28 (let ((triple (list s p o)))
29 (unless (member triple (cdr st))
30 (set-cdr! st (cons triple (cdr st))))
31 st))
32
33 (define (remove-triple st s p o)
34 ;; Remove the first triple matching (s p o) from store ST.
35 (let loop ((prev st) (curr (cdr st)))
36 (cond
37 ((null? curr) st)
38 ((and (equal? (caar curr) s)
39 (equal? (cadar curr) p)
40 (equal? (caddar curr) o))
41 (set-cdr! prev (cdr curr))
42 st)
43 (else
44 (loop curr (cdr curr))))))
45
46 (define (print-all-triples st)
47 ;; Display every triple in the store.
48 (display "All triples:\n")
49 (for-each (lambda (t)
50 (display " ")
51 (display (car t)) (display " ")
52 (display (cadr t)) (display " ")
53 (display (caddr t)) (newline))
54 (store-triples st))
55 (newline))
56
57 ;;;; ──────────────────────────────────────────────────────────────────
58 ;;;; 2. Tokenizer
59 ;;;; ──────────────────────────────────────────────────────────────────
60
61 (define (tokenize str)
62 ;; Split STR into SPARQL tokens, preserving <IRI> and "literal" strings atomically.
63 (let ((tokens '())
64 (buf '()))
65
66 (define (emit!)
67 (when (pair? buf)
68 (set! tokens (cons (list->string (reverse buf)) tokens))
69 (set! buf '())))
70
71 (let loop ((chars (string->list str)))
72 (if (null? chars)
73 (begin
74 (emit!)
75 (reverse tokens))
76 (let ((ch (car chars)))
77 (cond
78 ((char=? ch #\<)
79 (emit!)
80 (let read-iri ((cs (cdr chars)) (acc (list #\<)))
81 (cond
82 ((null? cs)
83 (set! tokens (cons (list->string (reverse acc)) tokens))
84 (loop '()))
85 ((char=? (car cs) #\>)
86 (set! tokens (cons (list->string (reverse (cons #\> acc))) tokens))
87 (loop (cdr cs)))
88 (else
89 (read-iri (cdr cs) (cons (car cs) acc))))))
90 ((char=? ch #\")
91 (emit!)
92 (let read-str ((cs (cdr chars)) (acc (list #\")))
93 (cond
94 ((null? cs)
95 (set! tokens (cons (list->string (reverse acc)) tokens))
96 (loop '()))
97 ((and (char=? (car cs) #\\) (pair? (cdr cs)))
98 (read-str (cddr cs) (cons (cadr cs) (cons #\\ acc))))
99 ((char=? (car cs) #\")
100 (set! tokens (cons (list->string (reverse (cons #\" acc))) tokens))
101 (loop (cdr cs)))
102 (else
103 (read-str (cdr cs) (cons (car cs) acc))))))
104 ((member ch '(#\( #\) #\{ #\} #\. #\, #\;))
105 (emit!)
106 (set! tokens (cons (string ch) tokens))
107 (loop (cdr chars)))
108 ((char-whitespace? ch)
109 (emit!)
110 (loop (cdr chars)))
111 (else
112 (set! buf (cons ch buf))
113 (loop (cdr chars)))))))))
114
115 ;;;; ──────────────────────────────────────────────────────────────────
116 ;;;; 3. SPARQL parser
117 ;;;; ──────────────────────────────────────────────────────────────────
118
119 (define (var? tok)
120 ;; True if TOK is a SPARQL variable (starts with '?').
121 (and (string? tok)
122 (> (string-length tok) 0)
123 (char=? (string-ref tok 0) #\?)))
124
125 ;; Drop leading tokens until test passes, return remaining list.
126 (define (drop-until pred lst)
127 (cond
128 ((null? lst) '())
129 ((pred (car lst)) lst)
130 (else (drop-until pred (cdr lst)))))
131
132 (define (parse-sparql query)
133 ;; Parse a minimal SELECT … WHERE { … } query.
134 ;; Returns two values: (vars patterns).
135 ;; vars – list of variable name strings (or '("*") for SELECT *)
136 ;; patterns – list of (s p o) patterns
137 (let* ((toks (tokenize query))
138 ;; advance to SELECT keyword
139 (after-select
140 (let ((rest (drop-until (lambda (t) (string-ci=? t "select")) toks)))
141 (if (null? rest) '() (cdr rest)))))
142
143 ;; collect SELECT variables (or * wildcard)
144 (let-values (((vars after-vars)
145 (if (and (pair? after-select)
146 (string=? (car after-select) "*"))
147 (values '("*") (cdr after-select))
148 (let loop ((ts after-select) (acc '()))
149 (if (or (null? ts) (not (var? (car ts))))
150 (values (reverse acc) ts)
151 (loop (cdr ts) (cons (car ts) acc)))))))
152
153 ;; skip to '{'
154 (let* ((after-brace
155 (let ((rest (drop-until (lambda (t) (string=? t "{")) after-vars)))
156 (if (null? rest) '() (cdr rest)))))
157
158 ;; read triple patterns until '}'
159 (let loop ((ts after-brace) (patterns '()))
160 (cond
161 ((null? ts)
162 (values vars (reverse patterns)))
163 ((string=? (car ts) "}")
164 (values vars (reverse patterns)))
165 (else
166 ;; consume s p o
167 (let* ((s (car ts))
168 (ts (cdr ts))
169 (p (if (pair? ts) (car ts) ""))
170 (ts (if (pair? ts) (cdr ts) '()))
171 (o (if (pair? ts) (car ts) ""))
172 (ts (if (pair? ts) (cdr ts) '()))
173 ;; optional trailing '.'
174 (ts (if (and (pair? ts) (string=? (car ts) "."))
175 (cdr ts) ts)))
176 (loop ts (cons (list s p o) patterns))))))))))
177
178 ;;;; ──────────────────────────────────────────────────────────────────
179 ;;;; 4. Query evaluation
180 ;;;; ──────────────────────────────────────────────────────────────────
181
182 ;; An environment (binding set) is an association list: ((var . val) ...)
183
184 (define (env-lookup var env)
185 ;; Return the value bound to VAR in ENV, or #f.
186 (let ((pair (assoc var env)))
187 (and pair (cdr pair))))
188
189 (define (env-extend var val env)
190 ;; Return a new env with VAR=VAL added, or #f on conflict.
191 (let ((existing (assoc var env)))
192 (cond
193 (existing
194 (if (equal? (cdr existing) val) env #f))
195 (else
196 (cons (cons var val) env)))))
197
198 (define (match-pattern pattern triple env)
199 ;; Try to unify one PATTERN with one TRIPLE given ENV.
200 ;; Returns extended env on success, #f on failure.
201 (let ((ps (car pattern)) (pp (cadr pattern)) (po (caddr pattern))
202 (ts (car triple)) (tp (cadr triple)) (to (caddr triple)))
203 (let* ((e1 (if (var? ps)
204 (env-extend ps ts env)
205 (and (equal? ps ts) env)))
206 (e2 (and e1
207 (if (var? pp)
208 (env-extend pp tp e1)
209 (and (equal? pp tp) e1))))
210 (e3 (and e2
211 (if (var? po)
212 (env-extend po to e2)
213 (and (equal? po to) e2)))))
214 e3)))
215
216 (define (join-patterns patterns triples envs)
217 ;; For each pattern in PATTERNS, extend every env in ENVS by matching
218 ;; against all TRIPLES. Returns the list of surviving envs.
219 (if (null? patterns)
220 envs
221 (let* ((pat (car patterns))
222 (rest (cdr patterns))
223 (new-envs
224 (apply append
225 (map (lambda (env)
226 (filter
227 (lambda (e) e) ;; remove #f
228 (map (lambda (triple)
229 (match-pattern pat triple env))
230 triples)))
231 envs))))
232 (join-patterns rest triples new-envs))))
233
234 (define (project-env vars env)
235 ;; Pick out only the selected VARS from ENV.
236 ;; Returns an alist ((var . val) ...).
237 (map (lambda (v) (cons v (env-lookup v env))) vars))
238
239 (define (sparql-select st query)
240 ;; Run a SELECT query against store ST.
241 ;; Returns a list of alists, each mapping variable names to values.
242 ;; With SELECT *, returns the full binding environment as an alist.
243 (let-values (((vars patterns) (parse-sparql query)))
244 (let* ((triples (store-triples st))
245 (solutions (join-patterns patterns triples (list '())))
246 (select-*? (and (= (length vars) 1)
247 (string=? (car vars) "*"))))
248 (map (lambda (env)
249 (if select-*?
250 env ;; full binding set
251 (project-env vars env)))
252 solutions))))
253
254 ;;;; ──────────────────────────────────────────────────────────────────
255 ;;;; 5. Display helpers
256 ;;;; ──────────────────────────────────────────────────────────────────
257
258 (define (display-results results)
259 ;; Pretty-print a list of query result alists.
260 (if (null? results)
261 (display " (no results)\n")
262 (for-each (lambda (row)
263 (display " ")
264 (for-each (lambda (pair)
265 (display (car pair))
266 (display ": ")
267 (display (cdr pair))
268 (display " "))
269 row)
270 (newline))
271 results)))
272
273 (define (run-query st label q)
274 (display "Query: ") (display label) (newline)
275 (display-results (sparql-select st q))
276 (newline))
277
278 ;;;; ──────────────────────────────────────────────────────────────────
279 ;;;; 6. Demo
280 ;;;; ──────────────────────────────────────────────────────────────────
281
282 (define (main . args)
283 (let ((st (make-store)))
284
285 ;; Load some data with real IRIs and mixed-case literals
286 (add-triple st "<http://example.org/Alice>" "<foaf:name>" "\"Alice Smith\"")
287 (add-triple st "<http://example.org/Alice>" "<foaf:knows>" "<http://example.org/Bob>")
288 (add-triple st "<http://example.org/Alice>" "<foaf:age>" "30")
289 (add-triple st "<http://example.org/Bob>" "<foaf:name>" "\"Bob Jones\"")
290 (add-triple st "<http://example.org/Bob>" "<foaf:age>" "25")
291 (add-triple st "<http://example.org/Carol>" "<foaf:name>" "\"Carol White\"")
292 (add-triple st "<http://example.org/Carol>" "<foaf:age>" "35")
293
294 (print-all-triples st)
295
296 ;; Who does Alice know, and what is their name?
297 (run-query st
298 "Who does Alice know?"
299 "SELECT ?friendName WHERE {
300 <http://example.org/Alice> <foaf:knows> ?friend .
301 ?friend <foaf:name> ?friendName .
302 }")
303
304 ;; All subjects and their names
305 (run-query st
306 "All names"
307 "SELECT ?s ?name WHERE {
308 ?s <foaf:name> ?name .
309 }")
310
311 ;; All subjects and their ages
312 (run-query st
313 "All ages"
314 "SELECT ?person ?age WHERE {
315 ?person <foaf:age> ?age .
316 }")
317
318 ;; SELECT * – return every binding
319 (run-query st
320 "SELECT * (all triples)"
321 "SELECT * WHERE { ?s ?p ?o . }")
322
323 ;; Remove a triple and verify
324 (display "After removing <http://example.org/Bob> <foaf:age> 25:\n")
325 (remove-triple st "<http://example.org/Bob>" "<foaf:age>" "25")
326 (run-query st
327 "All ages after removal"
328 "SELECT ?person ?age WHERE {
329 ?person <foaf:age> ?age .
330 }")))
Running the Demo and Using the Code
Running with make
The Makefile provides three targets. make run executes RDF.ss directly
under the Gerbil interpreter gxi. No compilation step is needed, making
this the quickest way to see the output. make compile invokes the Gerbil
compiler gxc, which compiles RDF.ss into native code and installs the
resulting module under the package name declared in gerbil.pkg
(rdf-datastore). After compiling, the module can be imported from any
other Gerbil file as :rdf-datastore/RDF. make clean removes all
compiled artefacts.
The Demo at the Bottom of RDF.ss
The bottom of RDF.ss defines a main function executed automatically
when the file is interpreted with gxi. Defining main rather than running
at top level ensures that importing :rdf-datastore/RDF as a library does
not run the demo side-effects. The demo builds a small social graph with three
people (Alice, Bob, and Carol) using real IRIs and mixed-case literals, each
with name and age triples, plus a foaf:knows link from Alice to Bob.
Five queries exercise the main features of the engine:
- A two-pattern join that finds the name of everyone Alice knows.
- A single-pattern scan that retrieves all subjects and their names.
- A single-pattern scan that retrieves all subjects and their ages.
- A
SELECT *query that returns every triple in the store as a full binding. - A post-deletion query that verifies the
remove-tripleoperation worked.
Looking at the output of each query against the data you loaded is the most direct way to build intuition for how SPARQL variable binding and joining work.
Here is sample program output:
1 $ make
2 gxi RDF.ss
3 All triples:
4 <http://example.org/Carol> <foaf:age> 35
5 <http://example.org/Carol> <foaf:name> "Carol White"
6 <http://example.org/Bob> <foaf:age> 25
7 <http://example.org/Bob> <foaf:name> "Bob Jones"
8 <http://example.org/Alice> <foaf:age> 30
9 <http://example.org/Alice> <foaf:knows> <http://example.org/Bob>
10 <http://example.org/Alice> <foaf:name> "Alice Smith"
11
12 Query: Who does Alice know?
13 ?friendName: "Bob Jones"
14
15 Query: All names
16 ?s: <http://example.org/Carol> ?name: "Carol White"
17 ?s: <http://example.org/Bob> ?name: "Bob Jones"
18 ?s: <http://example.org/Alice> ?name: "Alice Smith"
19
20 Query: All ages
21 ?person: <http://example.org/Carol> ?age: 35
22 ?person: <http://example.org/Bob> ?age: 25
23 ?person: <http://example.org/Alice> ?age: 30
24
25 Query: SELECT * (all triples)
26 ?o: 35 ?p: <foaf:age> ?s: <http://example.org/Carol>
27 ?o: "Carol White" ?p: <foaf:name> ?s: <http://example.org/Carol>
28 ?o: 25 ?p: <foaf:age> ?s: <http://example.org/Bob>
29 ?o: "Bob Jones" ?p: <foaf:name> ?s: <http://example.org/Bob>
30 ?o: 30 ?p: <foaf:age> ?s: <http://example.org/Alice>
31 ?o: <http://example.org/Bob> ?p: <foaf:knows> ?s: <http://example.org/Alice>
32 ?o: "Alice Smith" ?p: <foaf:name> ?s: <http://example.org/Alice>
33
34 After removing <http://example.org/Bob> <foaf:age> 25:
35 Query: All ages after removal
36 ?person: <http://example.org/Carol> ?age: 35
37 ?person: <http://example.org/Alice> ?age: 30
Package and Module Structure
gerbil.pkg declares the package name rdf-datastore. Gerbil uses this to
determine the import path of compiled modules. Once compiled, any other
Gerbil source file can bring the exported names (make-store, add-triple,
remove-triple, store-triples, sparql-select, and print-all-triples)
into scope with a single import form. This makes RDF.ss usable both as
a standalone runnable demo and as a reusable library component in a larger
Gerbil project.
Summary and Further Directions
RDF.ss demonstrates that the essential machinery of an RDF store and a pattern-matching query engine fits comfortably in a single, readable Gerbil Scheme source file with no external dependencies. The key ideas (triples as lists, environments as association lists, query evaluation as a recursive join) are each short enough to understand in isolation, yet they compose directly into a working system.
Several directions are natural next steps from this foundation:
- Persistence. The store could be serialized to and loaded from N-Triples (
.nt) format, the simplest RDF serialization, by writing a small line-by-line parser and a corresponding writer. - OPTIONAL patterns. SPARQL’s
OPTIONALclause implements a left outer join. It can be layered on top of the existing join infrastructure by keeping solutions that survive the optional pattern and also keeping the original environment for solutions that do not. - FILTER expressions. Numeric and string comparisons inside a
FILTERclause narrow results without adding new bindings. A small expression evaluator over the current environment would be sufficient. - Index structures. For larger datasets, a hash-table index on subject, predicate, or object would let
match-patternskip the full triple scan, dramatically reducing query time. - Named graphs. Extending each triple to a quad
(graph subject predicate object)and adding aFROMclause to the parser extends the model to the SPARQL 1.1 dataset model with minimal structural change.
Each of these extensions is a natural exercise in applied Scheme programming, and the clean separation of the data model, the parser, and the evaluator in RDF.ss makes them straightforward to add without rewriting the whole system.
Optional Practice Problems
- LIMIT Clause Support: Modify the SPARQL query parser and evaluator in
RDF.ssto parse and respect aLIMIT <integer>clause at the end of a SELECT query, restricting the number of returned result rows. - OPTIONAL Match Pattern: Implement support for
OPTIONAL { ... }blocks in the query evaluator, allowing queries to succeed and bind variables even if some of the optional triple patterns do not match. - N-Triples Importer: Write a function that reads an N-Triples file, parses each valid line into subject, predicate, and object strings, and inserts them into the in-memory RDF store.