Prolog Tutorial
Learn Prolog step by step: 40 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Prolog? Meet Prolog, the logic programming language: you state facts and rules, and the system finds answers by searching. See how it differs from Python, Java or C.
- Installing and Running SWI-Prolog Install SWI-Prolog, start the interactive toplevel, load a file with consult, read answers and press semicolon for more. Includes editors and online options.
- Prolog Syntax and Terms: Atoms, Numbers, Variables, Compounds Learn the building blocks of Prolog: atoms, numbers, strings, variables, compound terms, functor and arity, lists as terms, operators and comments.
- Your First Prolog Program: Hello World, write and format Write and run a first Prolog program: hello world, write/1, nl/0, format/2 directives, the main predicate, initialization and a loop over all answers with forall/2.
Facts, Rules and Queries
- Prolog Facts and Queries Learn how to write Prolog facts, build a small knowledge base and ask yes/no and variable queries. Covers predicates, arity, argument order and unknown procedures.
- Prolog Variables, Conjunction and Disjunction Understand Prolog variables, shared variables across goals, conjunction with a comma and disjunction with a semicolon. Learn how queries combine goals to join facts.
- Prolog Rules and Clauses: Heads, Bodies and Inference Learn how Prolog rules work: head :- body, variables shared between head and body, several clauses as alternatives, helper predicates and how Prolog proves a goal.
- Worked Example: A Family Tree in Prolog Build a complete Prolog family tree: facts for parents and gender, rules for father, sibling, uncle, cousin and more, with queries in every direction and common pitfalls.
- Prolog Closed-World Assumption and Negation as Failure Learn how Prolog treats missing facts as false, how \+ implements negation as failure, why goal order matters with negation, and how it differs from logical not.
Unification and Backtracking
- Prolog Unification: How Terms Match Understand unification, the pattern matching at the heart of Prolog: the rules for atoms, variables and compound terms, worked examples, lists, failure and the = operator.
- Prolog Term Comparison: =, ==, =:=, Standard Order and Type Checks Learn the difference between =, \=, ==, \==, =:= and is in Prolog, the standard order of terms with @< and compare/3, plus type tests like var, atom and ground.
- Prolog Proof Search Trees: How Prolog Finds Answers See exactly how Prolog proves a query: goal selection left to right, clause selection top to bottom, depth-first search trees, success and failure branches and infinite loops.
- Prolog Backtracking: Choice Points, Retry and Generate-and-Test Understand backtracking in Prolog: how choice points and the trail let the system undo bindings and retry alternatives, with fail loops, generate-and-test and findall.
- Tracing and Debugging Prolog: trace, spy, Ports and Error Messages Debug Prolog programs with trace, spy and debug/3. Learn the four-port model (call, exit, redo, fail), read typical error messages and fix singleton and instantiation errors.
Lists and Recursion
- Recursion in Prolog: Base Cases, Ancestors, Peano Numbers Learn how recursion works in Prolog with a base case and a recursive case: ancestor relations, factorial, Peano arithmetic, graph reachability and how to avoid infinite loops.
- Prolog Lists: Head, Tail and Recursion on Lists Learn Prolog lists: the [Head|Tail] pattern, empty list, nested lists and list recursion. Write length, sum, count and maximum predicates one clause per list shape.
- Prolog member/2, append/3, select/3 and Other List Relations Master Prolog's core list predicates: how member/2 and append/3 are defined, how append works in every direction, and how to build prefix, suffix, sublist and select from them.
- Prolog Accumulators, Reverse and Tail Recursion Learn the accumulator technique in Prolog: naive reverse versus accumulator reverse, tail recursion and last-call optimization, helper predicates and an intro to difference lists.
- Prolog Built-in List Predicates: length, nth, sort, maplist, foldl Tour of SWI-Prolog's list library: length, nth0, nth1, last, reverse, sum_list, msort, sort/4, list_to_set, delete, subtract, maplist, include, foldl and findall.
- Prolog List Patterns: Permutations, Subsets, Sorting and Puzzles Write classic Prolog list programs: permutation with select, subsequences and the power set, insertion sort, duplicate removal, zip and a seating puzzle solved by generate and test.
Arithmetic and Control
- Arithmetic and the is Operator Learn how Prolog does arithmetic. Why X = 2+3 does not give 5, how is/2 evaluates expressions, the arithmetic operators and functions, and how to write recursive numeric predicates.
- Comparing and Ordering Terms Understand the difference between =, ==, =:= and \=, learn the standard order of terms, and sort data with compare/3, sort/2, msort/2, sort/4, predsort/3 and keysort/2.
- The Cut: Controlling Backtracking Learn what the Prolog cut does, how it prunes choice points, the difference between green and red cuts, how to write deterministic predicates, and the classic mistakes to avoid.
- Negation, If-Then-Else and Loops Learn negation as failure with \+, the closed-world assumption, why goal order matters with negation, if-then-else with ->, and the control predicates once, ignore, forall, between and repeat.
Data Structures and Parsing
- Compound Terms and Structures Learn how Prolog builds data from compound terms. Use functor/3, arg/3, =.., copy_term/2, pairs and operators, and build a binary search tree out of nested structures.
- findall, bagof, setof and aggregate_all Collect all solutions of a goal in Prolog. Compare findall/3, bagof/3 and setof/3, understand free variables and the ^ operator, and count, sum and find maxima with aggregate_all/3.
- The Dynamic Database: assert and retract Change a Prolog program while it runs. Learn dynamic declarations, assertz, asserta, retract, retractall, the counter and memoization patterns, and when not to use the database.
- Atoms, Strings and Characters Work with text in Prolog. Learn the difference between atoms, strings and code lists, convert between them, and use atom_concat, sub_atom, split_string, atom_number and format/2.
- DCG Grammars and Parsing Parse and generate text with Prolog definite clause grammars. Learn the --> notation, phrase/2, terminals, extra arguments, curly-brace goals, an agreement grammar and an arithmetic parser.
- Input, Output and Error Handling Learn Prolog input and output with write, format, read and streams, work with files, and handle errors with catch/3 and throw/1, ISO error terms, must_be/2 and clean-up predicates.
Constraint Logic Programming
- Constraint Logic Programming with CLP(FD) Learn constraint logic programming over finite domains in Prolog. Use library(clpfd) with #=, in, ins and label/1, understand propagation, reversible arithmetic and reification.
- CLP(FD) Puzzles and Labeling Strategies Solve classic puzzles with Prolog constraints. Model SEND+MORE and N-queens with library(clpfd), choose labeling options such as ff and bisect, and learn modeling tips for faster search.
- Global Constraints and Optimization Go beyond simple constraints with CLP(FD). Use all_distinct, sum/3, element/3, global_cardinality, tuples_in, circuit and cumulative, and find optimal solutions with labeling min and max.
Applications
- Graph Search and Planning in Prolog Search graphs and state spaces in Prolog. Write paths with a visited list, breadth-first search with a queue, iterative deepening and weighted routes, then solve the water-jug puzzle as a planning problem.
- Meta-Interpreters and Expert Systems Write a Prolog interpreter in three lines with clause/2, extend it to build proof trees and count depth, then build a rule-based expert system that asks questions and explains its reasoning.
- Tabling and Performance Tuning Make Prolog programs fast. Use tabling for memoization and left recursion, write tail-recursive predicates with accumulators, avoid needless choice points, and measure with time/1 and statistics.
Projects and Practice
- Project: A Sudoku Solver with CLP(FD) Build a complete Sudoku solver in Prolog with library(clpfd). Model rows, columns and boxes with all_distinct, add a printer and a uniqueness check, then run the same model on a Python stand-in.
- Project: A Text Adventure Game Build a text adventure in Prolog. Model rooms and items as facts, keep the game state in the dynamic database, write commands as predicates, and parse typed input with a DCG.
- Debugging, Testing and Style in Prolog Find and fix Prolog bugs with the four-port tracer, spy points and debug/3, write unit tests with plunit, read common errors and warnings, and follow style rules that keep programs readable.
- Prolog Practice Problems with Solutions Sharpen your Prolog with sixteen graded exercises on lists, arithmetic, recursion, search, DCGs and constraints. Try each problem first, then compare with the worked solutions and runnable checks.