As my last contact with Prolog was over ten years ago, I think it’s time for some fun with Datomic and Datalog. In order to learn to know Datomic better, I will attempt to implement linked lists as a Datomic data structure.
First, I need a database “schema”, which in Datomic means that I have to define a few attributes. I’ll define one
:content/name (as a string) for naming my list items, and also the attributes for the list data structure itself, namely
:linkedList/tail (both are refs):
Next, I’ll create some sample data. I’ll define a simple list
(A, B, C, D):
Now, for some queries. Let’s warm up a bit first.
Finding all contents (not by list):
Finding the head of our list (knowing it starts with
Next we need a rule that defines when two list items are linked. The first thing that comes to mind is that two items are linked when one is the head and the other is the (head of the) tail. So:
Now I can query for the list item linked to
A, using this rule:
This will only return
B, of course. To get the whole list, I’ll need a recursive rule. Now how does that work? - Let’s see:
So, I say that two list items are linked when they are directly linked, or when there is an intermediate list item that recursively is linked to one and directly linked to the other input item.
Now what happens when I run the query from before with the new rule(s)? - Hmmm, I get
D, but am still missing the
How to include the
A, too, so that I get the complete list contents? - I’ll have to again extend the rules. Two list items should also be viewed as linked when they are the same:
These rules view two items as linked when they both are list items (insofar as they have the
:linkedList/head attribute), and they are equal. Or, as above, when the two items are linked via an intermediate item.
Finally, I get
D as a result. Of course, if I query like this, I won’t get them ordered. If I need them ordered, I’ll have to simply query one after the other, iterating through the list ourselves…
So, that’s all for today’s finger exercises…
In my humble opinion, Datomic is the best kind of NoSQL database I ever happened upon. It’s visionary: I’d absolutely love to do away with mutability (like Datomic does) in all my current projects with database backends…
I’ve also started a little project to create an easy-to-use Scala API for Datomic. I’m not yet sure which direction this will take, however. See here.