← back to programming

Logic Programming

Abelson & Sussman · 1996 · SICP §4.4

Programs as queries against a database of facts and rules. Unification matches patterns with variables. Programming becomes asking questions, not giving instructions.

( ?x 3 ) ?x 3 ( 5 3 ) 5 3 bind unification finds bindings that make two patterns equal

Deductive information retrieval

A database of assertions (facts) and rules (implications). A query is a pattern with variables. The system finds all ways to bind the variables so the pattern matches the database. This is Prolog's core idea.

Scheme

How the query system works — unification

Pattern matching is one-directional: the pattern has variables, the datum doesn't. Unification generalizes this: both sides can have variables. Two patterns unify if there exists a substitution that makes them equal. This is the engine behind Prolog and the query language.

Scheme

Rules — deduction from facts

A rule says: if you can satisfy the body, you can conclude the head. (rule (can-replace ?x ?y) (and (job ?x ?j) (job ?y ?j) (not (same ?x ?y)))). The query system chains rules to derive new facts from existing ones.

Scheme

Is logic programming mathematical logic?

Not quite. Logic programming uses a closed-world assumption: anything not in the database is false. Mathematical logic has no such default. Also, rule application order matters — an infinite loop is possible if rules are written carelessly. The query system is a computational interpretation of logic, not a faithful implementation.

Scheme

Implementing the query system

The query evaluator processes compound queries (and, or, not) by combining streams of bindings. An and query pipes the output of one sub-query into the next. An or query merges streams. not filters out bindings that succeed.

Scheme

Notation reference

Query language Python Meaning
(job ?x ?dept)for r in db if r[0]=="job"Query with pattern variables
(and q1 q2)set1 & set2Both queries must match
(or q1 q2)set1 | set2Either query matches
(not q)set1 - set2Negation as failure
(rule (head) body)def head(): bodyDerive new facts from existing
Neighbors

Other reading pages

Foundations (Wikipedia)

Translation notes

Logic programming inverts the usual programming flow: you specify what relates to what, and the system figures out how to compute it. Python has no built-in unification, so the translation uses explicit loops and set operations. Unification generalizes both pattern matching and equation solving. In Python, the closest built-in is dictionary merging, but it lacks the bidirectional variable binding that makes unification powerful.

Ready for the real thing? Read SICP §4.4.