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.
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.
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.
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.
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.
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.
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 & set2 | Both queries must match |
| (or q1 q2) | set1 | set2 | Either query matches |
| (not q) | set1 - set2 | Negation as failure |
| (rule (head) body) | def head(): body | Derive new facts from existing |
Neighbors
Other reading pages
- SICP Ch.16 — Nondeterministic Computing — backtracking as a language feature
- SICP Ch.18 — Register Machines — from high-level to hardware
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.