Logic programming

On this page 7

Logic programming is a declarative programming paradigm in which a program is a set of logical facts and rules, and computation consists of an inference engine deriving answers to queries from those statements. Within Symbolic AI & reasoning, it is the approach that turned formal logic into an executable language, so that knowledge written as rules can be queried directly instead of being encoded as step-by-step procedures.

The idea is often summarized by Robert Kowalski’s equation algorithm = logic + control: the programmer states what is true, and the system decides how to search for proofs. Prolog, Datalog and answer set programming are the best-known members of the family, and they remain important in artificial intelligence wherever explainable, rule-based reasoning is required.

How logic programs compute answers

A logic program computes by proving goals from clauses. Most classical systems restrict programs to Horn clauses, rules with at most one positive conclusion, written as head :- body. A fact such as parent(ann, bob). is a clause with an empty body, and a rule such as grandparent(X, Z) :- parent(X, Y), parent(Y, Z). states a conditional truth.

When a user poses a query, Prolog applies SLD resolution: it selects the leftmost goal, finds a clause whose head matches it through unification, and replaces the goal with that clause’s body. Unification computes the most general substitution that makes two terms identical, which is how variables receive values. If a branch fails, the engine backtracks to the most recent choice point and tries the next clause.

The following table names the core components and the role each plays in execution.

ComponentFormRole in computation
Factlikes(sam, tea).Unconditional statement stored in the database
Rulehead :- goal1, goal2.Derives the head when all body goals succeed
Query?- likes(sam, X).Goal the engine tries to prove
UnificationMatching of termsBinds variables to values or other terms
BacktrackingReturn to a choice pointEnumerates alternative solutions
Core components of a logic program

Because answers are logical consequences of the program, a single relation can often run in several directions. The same append/3 predicate can join two lists, split a list into parts or check a combination, a property called relational programming that procedural languages rarely offer.

Main logic programming languages and semantics

Logic programming is a family of languages that share clausal syntax but differ in semantics and evaluation strategy. The choice between them depends on whether a task needs general computation, scalable database queries or combinatorial search.

LanguageEvaluation strategyTypical use
PrologTop-down SLD resolution with backtrackingParsing, expert systems, symbolic computation
DatalogBottom-up fixpoint evaluationRecursive database queries, program analysis
Answer set programmingGrounding plus stable-model solvingScheduling, configuration, planning
Constraint logic programmingResolution with constraint solversResource allocation, timetabling
Inductive logic programmingLearning clauses from examplesRule discovery in structured data
Major logic programming languages compared

Semantics matter as much as syntax. Prolog uses negation as failure, meaning a goal is treated as false when it cannot be proved, which reflects the closed-world assumption. Answer set programming formalizes this with stable model semantics, while Datalog guarantees termination on finite databases by forbidding function symbols.

Logic programming compared with other paradigms

Logic programming differs from imperative and functional styles mainly in who controls the search. The programmer describes relationships, and the engine explores proofs, whereas other paradigms require explicit control flow.

ApproachProgram describesExecution model
Logic programmingRelations and rulesProof search over clauses
Imperative programmingSequences of state changesStep-by-step instructions
Functional programmingMathematical functionsExpression evaluation
Production rule systemsCondition-action rulesForward chaining over working memory
Automated theorem provingFull first-order formulasGeneral resolution or tableaux
Logic programming against neighboring approaches

Compared with production rule systems, Prolog is primarily goal-driven backward chaining, while engines built on the Rete algorithm are data-driven. Compared with general automated theorem proving, logic programming trades expressiveness for predictable, efficient execution by limiting programs to Horn clauses and a fixed search order.

Where logic programming is applied

Logic programming is applied where knowledge is naturally expressed as rules and answers must be traceable. Typical applications include natural language parsing with definite clause grammars, legal and regulatory reasoning, configuration of complex products, and static analysis tools that express data-flow facts in Datalog.

  • Expert systems that encode domain rules and explain each conclusion through its proof tree.
  • Program analysis frameworks that compute pointer and taint relations as recursive Datalog queries.
  • Combinatorial planning with answer set solvers for timetables, rosters and product variants.
  • Neuro-symbolic systems that combine learned perception with logical constraints and rules.

A practical decision table helps identify when the paradigm fits and which dialect to choose.

SituationRecommended choiceReason
Large recursive queries over stored factsDatalogGuaranteed termination and set-at-a-time evaluation
Hard combinatorial problem with many constraintsAnswer set programmingOptimized solvers and declarative constraints
Symbolic manipulation and parsingPrologFull Turing-complete language with terms
Heavy numeric optimizationMathematical programming solversLogic engines handle arithmetic weakly
Choosing a logic programming approach

Limitations and common pitfalls

The declarative ideal is only partly achieved in practice, because clause order and goal order affect termination in Prolog. A left-recursive rule can loop forever even though its logical reading is correct, so programmers must still reason about control.

SymptomCauseFix
Query never returnsLeft recursion under depth-first searchReorder goals or use tabling
Unexpected success with negationNegation as failure on unbound variablesBind variables before negated goals
Slow performance on large dataTuple-at-a-time backtrackingIndex arguments or move to Datalog
Unsound unification resultsMissing occurs checkEnable the occurs check where needed
Frequent problems and their fixes

Further limits include weak handling of uncertainty and probabilities, the effort of writing rules by hand known as the knowledge acquisition bottleneck, and the cut operator, which improves efficiency but breaks the purely logical reading of a program.

The simple explanation

Logic programming lets a computer answer questions from a list of facts and rules. You do not tell the machine each step. You tell it what is true, and it works out the answer by itself.

Think of a family tree. You write that Ann is Bob’s parent and Bob is Carla’s parent. You add one rule: a parent of a parent is a grandparent. Now you can ask who Carla’s grandparent is. The system finds the answer by reasoning, and it can show every step it used.

How it is used in practice

A software security team at a mid-sized company needs to find places where user input reaches a database query without sanitization. Instead of writing a custom checker, the team extracts facts from about two million lines of code, such as which variable flows into which function, and stores them as Datalog relations.

They then write about forty recursive rules that define a tainted flow: a value is tainted if it comes from a request parameter or flows from another tainted value without passing through a sanitizer. The Datalog engine evaluates these rules bottom-up and lists every path from an input to a query.

The analysis runs in minutes on each build and reports a few dozen candidate vulnerabilities, each with a traceable chain of derived facts. Engineers review those chains instead of the whole codebase, and new rules can be added in hours when a fresh vulnerability pattern appears.