RacketLogic-ProgrammingDatalogProlog

Logic Programming with Datalog in Racket | Schema Programming Part 17

2.51 min read
Md Nasim SheikhMd Nasim Sheikh
Share:

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.

Quick Quiz

Which keyword describes a statement that is always true in Datalog?

Md Nasim Sheikh
Written by

Md Nasim Sheikh

Software Developer at softexForge

Verified Author150+ Projects
Published:

You May Also Like