Logic Programming with Datalog in Racket | Schema Programming Part 17
Code on GitHub: All examples from this tutorial are available at racket-programming-series/17-logic-programming-datalog — clone the repo and follow along!
Most languages are imperative (do this) or functional (calculate this). Logic Programming is declarative: here are the facts, find the answer. Racket supports this natively with #lang datalog.
Advertisement
Facts and Rules
Datalog is a subset of Prolog. You define facts and rules.
#lang datalog
; Facts
parent(john, douglas).
parent(john, bob).
parent(douglas, anna).
; Rules
ancestor(A, B) :- parent(A, B).
ancestor(A, B) :- parent(A, X), ancestor(X, B).
Running Queries
Now we can ask questions!
ancestor(john, A)?
Output:
ancestor(john, douglas).
ancestor(john, bob).
ancestor(john, anna).
Mixing Racket and Datalog
You can embed Datalog queries inside normal Racket code using the datalog library interface.
#lang racket
(require datalog)
(define dl (make-theory))
(datalog! dl "parent(john, douglas).")
(datalog! dl "parent(john, bob).")
(display (datalog dl "parent(john, X)?"))
Advertisement
Summary
Racket allows you to switch paradigms effortlessly. If you have a problem that requires constraint solving or relationship querying, switch to #lang datalog instead of writing complex search algorithms.
Which keyword describes a statement that is always true in Datalog?
Md Nasim Sheikh
Software Developer at softexForge