Debugging Prolog

Table of Contents

toggle-theme.png

Question

How do I debug my Prolog queries?

Debugging Prolog can be done pretty easily using a built-in tool called trace. Now, since the online swish editor for Prolog is fantastic, I’ll be assuming you’re using that, but this can all be done using swipl from your terminal as well.

Let’s say you have the following dataset:

parent(tom, adam).
parent(tom, alex).
parent(tom, luna).
parent(mel, adam).
parent(mel, alex).
parent(mel, luna).

sibling(X,Y):- 
    parent(P, X), parent(P, Y), X \= Y.

And we want to track down an error in our sibling rule. When querying against this rule, we can prefix our query with trace/0 to interactively follow what Prolog is doing:

?- trace, sibling(X, adam).

This will allow us to step through our code using step-into, step-over, step-out and retry, just like when we’re debugging in Java.

trace is the main tool that I use for debugging Prolog, but there’s a number of other tools that you can use here to learn how to debug Prolog better, all of which are explained in the swi-prolog documentation

Author: Philip Dumaresq

Email: phdumaresq@protonmail.com

Created: 2021-03-13 Sat 19:09