Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 40 ยท Projects and Practice

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 programs fail in ways that other languages do not. A predicate that "does nothing" has simply failed, a program can loop forever without a single wrong line of arithmetic, and the same query may give different answers when you reorder two goals. This lesson gives you a working method: read the messages, trace when you are lost, write tests so that bugs stay fixed, and follow a few style rules that prevent many of them.

Prolog is not available on this site, so the Prolog code and toplevel transcripts are read-only. The runnable demos use the stand-in interpreter (a Python program that supports facts, rules, clause/2 and the cut): one builds a tracer in Prolog itself, and one is a tiny test runner.

Read the messages first

SWI-Prolog tells you a lot when you load a file. Do not ignore warnings:

Message Meaning Usual fix
Singleton variables: [X] a variable appears only once a typo, or write _X / _ if intended
Clauses of foo/2 are not together discontiguous clauses keep clauses of one predicate together
Unknown procedure: foo/1 (existence error) no such predicate a misspelled name or wrong arity
Arguments are not sufficiently instantiated unbound variable where a value is needed reorder goals; see Arithmetic and is
Type error: ... expected, found ... wrong kind of argument check the data flowing in
Stack limit (1.0Gb) exceeded usually infinite recursion look for left recursion or a missing base case
Syntax error: Operator expected missing comma, full stop or bracket check the line named in the message

The first message is the most valuable and the most often ignored: a singleton warning is how Prolog tells you that you mistyped a variable name, and a mistyped variable is the most common Prolog bug.

list_undefined/0 (or check/0) after loading finds predicates that are called but never defined. Use listing(Name) to see the clauses Prolog actually has, which exposes misparsed code and clauses that were silently overwritten.

The four-port tracer

A Prolog call has four ports:

flowchart LR
  C["Call"] --> P(("predicate"))
  P --> E["Exit"]
  P --> F["Fail"]
  R["Redo"] --> P

Call: entered for the first time. Exit: succeeded. Fail: no more solutions. Redo: backtracked into to find another.

Switch the tracer on with trace/0, run a query, and Prolog stops at each port:

PROLOG
?- trace, grand(tom, W).
   Call: (12) grand(tom, _10392) ? creep
   Call: (13) parent(tom, _11120) ? creep
   Exit: (13) parent(tom, bob) ? creep
   ...

At each stop you press a key: Enter (or c) to creep one step, s to skip the whole call, l to leap to the next spy point, a to abort, +/- to set or remove a spy point on the current goal, h for help. Turn it off with notrace. The numbers are call depths, and the long variable names (_10392) are generated.

Tracing every step is slow, so combine it with spy points: spy(parent/2) stops only when parent/2 is called; nospy(parent/2) removes it; nodebug clears everything. In an IDE or with gtrace/0, a graphical tracer shows the same ports as a stack.

The fastest way to understand the tracer is to build one. A trace is just a meta-interpreter (Meta-Interpreters) that prints before and after each call:

Python A tiny tracer written in Prolog (Python stand-in interpreter)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the first transcript like a story: grand calls parent(tom, Y), which exits with bob; the second parent exits with ann, and grand exits, which is the first answer. Asking for more resumes the second parent call, which finds pat. When no alternative is left, the fail lines appear from the innermost goal outwards. The second query shows a failure from the very first parent(ann, Y): the goal grand(ann, W) has no solutions because Ann has no children. (This little tracer does not print the Redo port; the real one does.)

Printing while you debug

Sometimes format(user_error, "X = ~w~n", [X]) in the middle of a clause is faster than the tracer. SWI-Prolog has a nicer tool, debug/3:

PROLOG
walk(X, Y, V, P) :-
    debug(walk, "at ~w, visited ~w", [X, V]),
    ...

Messages appear only after debug(walk) is called and disappear after nodebug(walk), so you can leave them in the code. assertion(Goal) throws an error with a backtrace if a condition you believe must hold is false: a one-line way to catch violated assumptions early.

Unit tests with plunit

Debugging finds a bug once; a test keeps it fixed. SWI-Prolog ships with plunit:

PROLOG
:- use_module(library(plunit)).

:- begin_tests(double).

test(double_four)            :- double(4, 8).
test(double_zero, X == 0)    :- double(0, X).
test(negative, X == -6)     :- double(-3, X).
test(no_such, fail)          :- double(4, 9).
test(bad_type, error(type_error(evaluable, a/0))) :- double(a, _).
test(all_members, all(X == [1, 2, 3])) :- member(X, [1, 2, 3]).

:- end_tests(double).
PROLOG
?- run_tests.
% All 6 tests passed

The word after the test name is an option: X == Value compares the result, fail expects failure, error(Formal) or throws(Ball) expects an exception, all(X == List) checks every solution, nondet allows a test to leave choice points (otherwise plunit warns), and true(Goal) runs an arbitrary check. Put tests in a .plt file or beside the code, and run them from the command line with swipl -g run_tests -t halt file.pl so a build can fail on a broken test.

The stand-in below is a miniature of the idea: a list of cases, a runner that calls each in a catch, and a report. Notice how it classifies a wrong answer, an exception and a missing solution differently.

Python A tiny test runner (Python stand-in interpreter)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Style that prevents bugs

  • Name relations, not actions. parent(X, Y), list_length(List, N), sorted(Xs, Ys): the name should read as a true statement about its arguments. Avoid get_name and calculate.
  • Put inputs first, outputs last (double(+X, -Y)), as the standard library does, and document modes with + (input), - (output) and ? (either) in a PlDoc comment: %! double(+X, -Y) is det.
  • One goal per line, four-space indentation, a blank line between predicates, clauses of a predicate together, short clauses. Long bodies are a sign that a helper predicate is waiting to be named.
  • Use _Name for deliberately unused variables so the singleton warning keeps meaning something.
  • Keep the logic pure. Put I/O and assert at the edges; keep the core as relations that work in several directions, so they are easy to test.
  • Prefer if-then-else or mutually exclusive clauses over cuts. If you must cut, comment why. See The Cut.
  • Make determinism visible. In SWI-Prolog 9 you can write :- det(foo/2). to say a predicate must succeed exactly once; the system then checks it. Leftover choice points are a frequent cause of wrong "second" answers.
  • Write the base case first and put the cheapest, most selective goals early.
  • Check input with must_be/2 at the boundary of your library.
  • Test small, test early. A predicate that is verified on [], [a] and [a,b] is verified on all lists, if the recursion is right.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a 'Singleton variables' warning usually indicate?

    A variable used only once can never link two places, so it is almost always a typo.
  2. 2. Which tracer port is shown when Prolog backtracks into a predicate to look for another solution?

    Redo means an earlier call is resumed to produce its next solution.
  3. 3. How do you tell plunit that a test must fail?

    The fail option states that the goal must have no solution; error(Formal) expects an exception.
  4. 4. Why use debug/3 instead of format for diagnostic output?

    debug(Topic, ...) messages print only when debug(Topic) is active, so they can stay in the source.

Summary

  • Read warnings and errors: singletons, discontiguous clauses and existence errors are the usual first bugs.
  • trace/0, spy/1 and debug/3 show the Call, Exit, Fail and Redo ports; a tracer is just a meta-interpreter.
  • Use plunit to turn every fixed bug into a test: X == V, fail, error(E) and all(X == L) cover most cases.
  • Style: relation names, inputs first, pure core with I/O at the edges, few cuts, visible determinism.

Next: Practice Problems and Solutions