Programming Search⌘K

Conceptcore

Logic programming

Also called Prolog style, relational programming, Horn clause programming, Datalog, rule-based programming.

Logic programming writes a program as facts and rules in logic, and runs it by asking queries that an engine answers by unification and search, or by deriving facts until nothing changes.

Applies to
core-languages

Idea

Logic programming writes a program as a set of facts and rules in a logical form, and runs it by asking questions. An engine searches for values that make a question true, using the facts and the rules. Robert Kowalski, one of the founders of the field, put the main point like this: "A consequence of using logic to represent knowledge is that such knowledge can be understood declaratively. A consequence of using deduction to derive consequences in a computational manner is that the same knowledge can also be understood procedurally."1 The example below is a small engine in Python. It has three facts about parents, two rules that define ancestor, and a search that answers questions about them:

parent = [("zeus", "ares"), ("ares", "harmonia"), ("harmonia", "semele")]

# Each clause is (head, body). Names that start with a capital letter are variables.
clauses = [(("parent", a, b), []) for a, b in parent] + [
    (("ancestor", "X", "Y"), [("parent", "X", "Y")]),
    (("ancestor", "X", "Y"), [("parent", "X", "Z"), ("ancestor", "Z", "Y")]),
]


def walk(t, s):
    while t[0].isupper() and t in s:
        t = s[t]
    return t


def unify(a, b, s):
    if len(a) != len(b):
        return None
    for x, y in zip(a, b):
        x, y = walk(x, s), walk(y, s)
        if x == y:
            continue
        if x[0].isupper():
            s = {**s, x: y}
        elif y[0].isupper():
            s = {**s, y: x}
        else:
            return None
    return s


def solve(goals, s, depth=0):
    if not goals:
        yield s
        return
    for head, body in clauses:
        rename = lambda term: tuple(f"{t}{depth}" if t[0].isupper() else t for t in term)
        s2 = unify(goals[0], rename(head), s)
        if s2 is not None:
            yield from solve([rename(g) for g in body] + goals[1:], s2, depth + 1)


print([walk("Who", s) for s in solve([("ancestor", "zeus", "Who")], {})])
print([walk("Who", s) for s in solve([("ancestor", "Who", "semele")], {})])
print(any(solve([("ancestor", "semele", "zeus")], {})))
Output
['ares', 'harmonia', 'semele']
['harmonia', 'zeus', 'ares']
False

In Prolog, the same program is five lines: parent(zeus, ares). and two more facts, then ancestor(X, Y) :- parent(X, Y). and ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y). The rules do not say which argument is the input. The first question gives the ancestor and asks for the descendants. The second question gives the descendant and asks for the ancestors. The third question gives both and asks for a yes or a no. One definition answers all three.

How it works

Facts, rules and queries. A fact states that a relation holds, such as parent(zeus, ares). A rule states that a relation holds if other relations hold: ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y) reads "X is an ancestor of Y if X is a parent of some Z and Z is an ancestor of Y". Facts and rules of this form are Horn clauses: each has at most one conclusion. A query is a list of goals with variables, and an answer is a set of values for the variables that makes all the goals true.

Unification. The engine matches a goal against the head of a clause by unification. Unification finds a substitution that makes two terms equal, binding variables on both sides. In the example, unify and walk do this for flat terms. A full engine also unifies nested terms such as lists and records, which is how Prolog programs build and take apart data.

Top-down search with backtracking. Prolog proves a query from the goal down. It takes the first goal, tries the clauses in the order of the program, and for each clause whose head unifies, replaces the goal with the body of the clause. When a goal has no more clauses to try, the engine goes back to the last choice and tries the next clause. This is depth-first search, and in the example the Python generators give the backtracking for free: yield from resumes the search for the next answer. Each use of a clause gets fresh variables, which is the job of rename.

Logic plus control. Kowalski wrote that "an algorithm can be regarded as consisting of a logic component, which specifies the knowledge to be used in solving problems, and a control component, which determines the problem-solving strategies by means of which that knowledge is used."2 In Prolog, the logic is the clauses and the control is the fixed search order: clauses from top to bottom, goals from left to right. The same paper shows that one set of Horn clauses can run top-down, from the goal, or bottom-up, from the facts.

Bottom-up evaluation. Datalog is a subset of Prolog without nested terms, and its engines usually run bottom-up. The engine applies every rule to the known facts, adds the new facts, and repeats until no rule gives a new fact. The result is the least fixpoint of the rules. The Soufflé documentation shows the standard example, transitive closure over a graph: path(x, y) :- edge(x, y). and path(x, y) :- path(x, z), edge(z, y).3 Bottom-up evaluation always terminates in Datalog, because the set of possible facts is finite, and the order of the clauses does not change the answer. The examples in the other languages on this page use this method.

Negation as failure. Horn clauses cannot state that something is false. Prolog adds \+ Goal, which succeeds when the search for Goal fails. This is negation as failure: the engine assumes that what it cannot prove is false, which is the closed-world assumption of databases. It is correct only when the goal has no unbound variables at the time of the call.

In languages

LanguageVerdictNote
PythonIdiom
C++Absent
JavaAbsent
CAbsent
C#Absent
JavaScriptAbsent
TypeScriptAbsentAs JavaScript; the type checker solves constraints on types, but programs have no logic engine.
GoAbsent
RustAbsent
KotlinAbsentNo logic engine in the language or the standard library; JVM libraries provide rule engines and Prolog systems; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLIdiomA recursive common table expression computes the least fixpoint of a rule, as Datalog does, and the Python example runs one in SQLite.
BashAbsentThe shell has no relations, unification or search; join and awk can compute a join of two files, but not a recursive rule.
PowerShellAbsentNo logic engine; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML has no relations or rules.
CSSDoes not applyCSS has selectors that match elements, but no relations or rules that derive new facts.
Regular expressionsDoes not applyA regex engine backtracks over a pattern, but a regular expression has no relations or rules.
Language Verdict Mechanism
Python idiom generators for backtracking; recursive CTEs in sqlite3
JavaScript absent a fixpoint loop over a Set; Prolog engines in libraries
TypeScript absent as JavaScript
Java absent a fixpoint loop over a TreeSet; rule engines in libraries
Kotlin absent as Java
C# absent a fixpoint loop with a LINQ join
Go absent a fixpoint loop over a map used as a set
Rust absent a fixpoint loop over a BTreeSet; Datalog in crates
C absent a relation as a matrix of Booleans
C++ absent a fixpoint loop over a std::set
Bash absent no relations or rules
PowerShell absent no relations or rules
SQL idiom WITH RECURSIVE computes the fixpoint of a rule
Regex n/a backtracking over a pattern, but no relations
HTML n/a no rules
CSS n/a no rules that derive facts

None of the core languages has a logic engine. Logic programming lives in its own languages: Prolog and its descendants, Datalog engines such as Soufflé, and answer set programming systems. Programs in other languages use it in two ways. They embed an engine, such as a Prolog interpreter or a rule engine in a library, or they write the search or the fixpoint by hand, as the examples on this page do.

SQL is the closest of the core languages. The SQLite documentation says: "Recursive common table expressions provide the ability to do hierarchical or recursive queries of trees and graphs, a capability that is not otherwise available in the SQL language."4 A recursive common table expression has a base case and a recursive case, like the two clauses of ancestor, and with UNION the engine stops when no new row appears. This is bottom-up Datalog evaluation of one rule. The Python file of this page shows it.

The same ideas appear inside tools that programmers use every day. A type checker that infers types solves equations between type terms by unification, as in Hindley-Milner type inference. The Rust compiler finds trait implementations by a search over impls that works like a logic program. Static analysis tools often express their rules in Datalog, and so do some access control and policy systems.

PythonGitHub
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE parent (p TEXT, c TEXT)")
db.executemany("INSERT INTO parent VALUES (?, ?)",
               [("zeus", "ares"), ("ares", "harmonia"), ("harmonia", "semele"), ("semele", "dionysus")])

query = """
WITH RECURSIVE ancestor(a, d) AS (
    SELECT p, c FROM parent
    UNION
    SELECT parent.p, ancestor.d FROM parent JOIN ancestor ON parent.c = ancestor.a
)
SELECT d FROM ancestor WHERE a = 'zeus' ORDER BY d
"""
print([row[0] for row in db.execute(query)])
Output
['ares', 'dionysus', 'harmonia', 'semele']

This code runs but gives a wrong answer on purpose.

parent = [("zeus", "ares"), ("ares", "harmonia")]


def parent_of(x, y):
    for a, b in parent:
        if x in (None, a) and y in (None, b):
            yield a, b


def ancestor(x, y):
    for a, z in ancestor(x, None):
        for _, b in parent_of(z, y):
            yield a, b
    yield from parent_of(x, y)


try:
    print(list(ancestor("zeus", None)))
except RecursionError:
    print("RecursionError")
Output
RecursionError
  • Verdict: idiom. Python has no logic engine in the standard library, but generators give the backtracking search of Prolog (see the first block of the page), and SQLite's recursive common table expressions compute the same answers as Datalog rules.
  • The UNION in the query removes duplicate rows, so the recursion stops when no new pair appears. This is the fixpoint of the rule.
  • In the wrong block, the recursive rule calls itself before it reads any fact. A top-down search, as in Prolog, then calls ancestor forever. Put the fact first and the recursive goal last, or use a bottom-up engine such as Datalog, which does not have this problem.
#include <iostream>
#include <set>
#include <string>
#include <utility>
#include <vector>

int main() {
    using Fact = std::pair<std::string, std::string>;
    const std::vector<Fact> parent{{"zeus", "ares"}, {"ares", "harmonia"}, {"harmonia", "semele"}, {"semele", "dionysus"}};

    std::set<Fact> ancestor(parent.begin(), parent.end());
    for (bool changed = true; changed;) {
        changed = false;
        std::vector<Fact> derived;
        for (const auto& [x, z] : parent)
            for (const auto& [z2, y] : ancestor)
                if (z == z2) derived.emplace_back(x, y);
        for (auto& f : derived) changed |= ancestor.insert(std::move(f)).second;
    }
    std::cout << ancestor.size() << "\n";
    for (const auto& [x, y] : ancestor)
        if (y == "dionysus") std::cout << x << " ";
    std::cout << "\n";
}
Output
10
ares harmonia semele zeus 
  • Verdict: absent. C++ has no logic engine. Template metaprogramming and the overload resolution of the compiler perform a kind of search, but programs that need logic programming embed a Prolog or Datalog engine.
JavaGitHub
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class Main {
    record Pair(String x, String y) implements Comparable<Pair> {
        public int compareTo(Pair o) {
            int c = x.compareTo(o.x);
            return c != 0 ? c : y.compareTo(o.y);
        }
    }

    public static void main(String[] args) {
        List<Pair> parent = List.of(new Pair("zeus", "ares"), new Pair("ares", "harmonia"),
                new Pair("harmonia", "semele"), new Pair("semele", "dionysus"));

        Set<Pair> ancestor = new TreeSet<>(parent);
        boolean changed = true;
        while (changed) {
            changed = false;
            for (Pair p : parent) {
                for (Pair a : List.copyOf(ancestor)) {
                    if (p.y().equals(a.x())) {
                        changed |= ancestor.add(new Pair(p.x(), a.y()));
                    }
                }
            }
        }
        System.out.println(ancestor.size());
        ancestor.stream().filter(a -> a.x().equals("ares")).forEach(a -> System.out.println(a.y()));
    }
}
Output
10
dionysus
harmonia
semele
  • Verdict: absent. Java has no logic engine in the language or the JDK. Rule engines such as Drools, and Prolog systems that run on the JVM, are libraries.
#include <stdbool.h>
#include <stdio.h>

enum { ZEUS, ARES, HARMONIA, SEMELE, DIONYSUS, N };
static const char *name[N] = { "zeus", "ares", "harmonia", "semele", "dionysus" };

int main(void)
{
    bool parent[N][N] = { 0 }, ancestor[N][N] = { 0 };
    parent[ZEUS][ARES] = parent[ARES][HARMONIA] = true;
    parent[HARMONIA][SEMELE] = parent[SEMELE][DIONYSUS] = true;

    for (int x = 0; x < N; x++)
        for (int y = 0; y < N; y++)
            ancestor[x][y] = parent[x][y];

    for (bool changed = true; changed;) {
        changed = false;
        for (int x = 0; x < N; x++)
            for (int z = 0; z < N; z++)
                for (int y = 0; y < N; y++)
                    if (parent[x][z] && ancestor[z][y] && !ancestor[x][y])
                        ancestor[x][y] = changed = true;
    }

    int count = 0;
    for (int x = 0; x < N; x++)
        for (int y = 0; y < N; y++)
            count += ancestor[x][y];
    printf("%d\n", count);
    for (int y = 0; y < N; y++)
        if (ancestor[ZEUS][y])
            printf("%s ", name[y]);
    printf("\n");
    return 0;
}
Output
10
ares harmonia semele dionysus 
  • Verdict: absent. C has no logic engine. With a small, fixed set of constants, a relation fits in a matrix of Booleans, and the rule becomes a triple loop.
var parent = new[] { ("zeus", "ares"), ("ares", "harmonia"), ("harmonia", "semele"), ("semele", "dionysus") };

var ancestor = new HashSet<(string X, string Y)>(parent);
bool changed = true;
while (changed)
{
    var derived = (from p in parent
                   from a in ancestor
                   where p.Item2 == a.X
                   select (p.Item1, a.Y)).ToList();
    changed = false;
    foreach (var fact in derived)
    {
        changed |= ancestor.Add(fact);
    }
}
Console.WriteLine(ancestor.Count);
Console.WriteLine(string.Join(",", ancestor.Where(a => a.Y == "semele").Select(a => a.X).Order()));
Output
10
ares,harmonia,zeus
  • Verdict: absent. C# has no logic engine. The LINQ query is the join in the body of the recursive rule, and the loop runs it until the set of facts stops growing.
JavaScriptGitHub
const parent = [["zeus", "ares"], ["ares", "harmonia"], ["harmonia", "semele"], ["semele", "dionysus"]];

// ancestor(X, Y) :- parent(X, Y).
// ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).
const ancestor = new Set(parent.map(([x, y]) => `${x} ${y}`));
let changed = true;
while (changed) {
  changed = false;
  for (const [x, z] of parent) {
    for (const fact of [...ancestor]) {
      const [z2, y] = fact.split(" ");
      if (z === z2 && !ancestor.has(`${x} ${y}`)) {
        ancestor.add(`${x} ${y}`);
        changed = true;
      }
    }
  }
}
console.log(ancestor.size);
console.log([...ancestor].filter((f) => f.endsWith(" dionysus")).map((f) => f.split(" ")[0]).sort());
Output
10
[ 'ares', 'harmonia', 'semele', 'zeus' ]
  • Verdict: absent. JavaScript has no logic engine. The loop applies the two rules until no new fact appears, which is how a bottom-up Datalog engine works. Libraries such as Tau Prolog run Prolog in JavaScript.
package main

import (
	"fmt"
	"sort"
)

type pair struct{ x, y string }

func main() {
	parent := []pair{{"zeus", "ares"}, {"ares", "harmonia"}, {"harmonia", "semele"}, {"semele", "dionysus"}}

	ancestor := map[pair]bool{}
	for _, p := range parent {
		ancestor[p] = true
	}
	for changed := true; changed; {
		changed = false
		for _, p := range parent {
			for a := range ancestor {
				if p.y == a.x && !ancestor[pair{p.x, a.y}] {
					ancestor[pair{p.x, a.y}] = true
					changed = true
				}
			}
		}
	}

	var below []string
	for a := range ancestor {
		if a.x == "harmonia" {
			below = append(below, a.y)
		}
	}
	sort.Strings(below)
	fmt.Println(len(ancestor), below)
}
Output
10 [dionysus semele]
  • Verdict: absent. Go has no logic engine. A map used as a set holds the facts, and the loop is a naive bottom-up evaluation of the rules.
  • Adding to a map while ranging over it is allowed in Go, but the new entries may or may not be visited in the same loop. The outer loop repeats until nothing changes, so the result is still complete.
RustGitHub
use std::collections::BTreeSet;

fn main() {
    let parent = [("zeus", "ares"), ("ares", "harmonia"), ("harmonia", "semele"), ("semele", "dionysus")];

    let mut ancestor: BTreeSet<(&str, &str)> = parent.iter().copied().collect();
    loop {
        let derived: Vec<_> = parent
            .iter()
            .flat_map(|&(x, z)| ancestor.iter().filter(move |&&(z2, _)| z2 == z).map(move |&(_, y)| (x, y)))
            .collect();
        let before = ancestor.len();
        ancestor.extend(derived);
        if ancestor.len() == before {
            break;
        }
    }
    println!("{}", ancestor.len());
    let roots: Vec<_> = ancestor.iter().filter(|&&(_, y)| y == "harmonia").map(|&(x, _)| x).collect();
    println!("{roots:?}");
}
Output
10
["ares", "zeus"]
  • Verdict: absent. Rust has no logic engine in the language. The trait solver of the compiler is itself a logic program over impls, and crates such as datafrog and ascent give Datalog to Rust programs.
  • Prolog. The first and most used logic programming language, with top-down search, backtracking, nested terms and the cut (!), which removes choice points to control the search.
  • Datalog. A restricted logic language with no nested terms, evaluated bottom-up. It is used for program analysis, queries over graphs and deductive databases.
  • Constraint logic programming. Variables can range over integers, reals or finite domains, and the engine keeps constraints such as X + Y #= 10 and solves them. Many Prolog systems include it.
  • Answer set programming. A program defines stable models, and a solver finds them. It is used for planning, scheduling and configuration problems.
  • miniKanren. The miniKanren site describes it as "a family of Domain Specific Languages for logic programming",5 small enough to embed in a host language as a library.
  • Functional logic languages. Curry and Mercury join functions and relations with types and modes, which say which arguments are inputs.
  • Pattern matching. Matching is one-way unification: the pattern has variables, but the value does not. See pattern matching.
  • Declarative programming. Logic programming is one branch of declarative programming, next to functional programming and query languages.

Pitfalls

  • Left recursion. A rule that calls itself as its first goal, such as ancestor(X, Y) :- ancestor(X, Z), parent(Z, Y), makes a top-down engine loop forever. The rule is logically correct, but the control is wrong. The wrong block in the Python file shows the result. Datalog engines and tabling in some Prolog systems do not have this problem.
  • Order matters in Prolog. The logic does not depend on the order of clauses and goals, but termination and speed do. A goal that binds a variable must come before a goal that tests it.
  • Negation as failure with unbound variables. \+ member(X, [1, 2]) fails when X is unbound, because some X is a member. Call negation only after the goal is ground.
  • The cut. ! makes programs faster but removes answers. A cut in the wrong place makes a relation work in one direction only, or makes it give wrong answers.
  • Exponential search. A depth-first search can try the same subgoal many times. Memoization (tabling) or a bottom-up engine prevents the repeated work.
  • Missing occurs check. For speed, most Prolog systems unify X with f(X) and make a cyclic term. The result is not a logical answer. Use unify_with_occurs_check where this matters.
  • Arithmetic is not relational. X is Y + 1 in Prolog needs Y to be bound. Constraint libraries give relations over numbers that run in all directions.

Cost

A top-down search costs time in proportion to the number of nodes in its search tree, which can be exponential in the size of the problem. Each step unifies terms and records bindings so that it can undo them on backtracking. Well-built Prolog systems compile clauses to instructions for an abstract machine, the Warren Abstract Machine, and index clauses on their first argument, so a simple deterministic predicate runs almost as fast as a function in a compiled language. Naive bottom-up evaluation, as in the examples on this page, repeats old joins in each round. Semi-naive evaluation joins only the new facts of the last round, and engines such as Soufflé compile the rules to parallel C++ with indexes. A Datalog program without negation and nested terms always terminates, and its cost is polynomial in the number of facts.

History

Logic programming grew from work on automatic theorem proving. In 1965, J. Alan Robinson published the resolution principle, with unification as its central step. In 1971 and 1972, Alain Colmerauer and his group in Marseille built a language for processing natural language, and Kowalski in Edinburgh gave it a procedural reading of Horn clauses. Colmerauer and Philippe Roussel wrote that they had "a preliminary version of Prolog at the end of 1971 and a more definitive version at the end of 1972".6 Kowalski recalls that the name "was suggested by Roussel's wife, Jacqueline, as an abbreviation for programmation en logique."1 David H. D. Warren's compiler for DEC-10 Prolog in 1977 made Prolog fast enough for real programs, and his abstract machine of 1983 became the base of most later systems. Kowalski's paper "Algorithm = Logic + Control" appeared in 1979.2 Japan's Fifth Generation Computer Systems project used logic programming as its base from 1982 to 1992. Prolog became an ISO standard in 1995. Datalog came from deductive database research in the 1980s and returned in the 2010s as a language for program analysis and for queries over graphs.

References

  1. The Early Years of Logic Programming, Robert Kowalski, Communications of the ACM 31(1), 1988, Introduction; Marseille
  2. Algorithm = Logic + Control, Robert Kowalski, Communications of the ACM 22(7), 1979, abstract; top-down and bottom-up interpretations
  3. A Simple Example, Soufflé documentation, transitive closure
  4. The WITH Clause, SQLite documentation, 3. Recursive Common Table Expressions
  5. miniKanren, introduction
  6. The birth of Prolog, Alain Colmerauer and Philippe Roussel, 1992, introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/A1QFCK/text.yaml