5
votes

I'm very new to Prolog (started to learn for two weekish) and our assignment that involves hamiltonian path is going to drive me insane especially when I'm debugging the problem. In haskell, there was a debug trace u can do so that everytime a function runs, it spits out whatever values I want so I know what goes in and what goes out and guess where the number is going haywire.

Could something similar exist in Prolog? Googled it but I'm doing something wrong cause I'm not having any luck so far. Welp.

2
See this for more. – false

2 Answers

7
votes

There are several options:

0. "Poor person's trace": Impure output

You can use impure predicates like format/2 to emit debug information from within your programs.

Example:

?- X = 4, format("X is now: ~w\n", [X]).
X is now: 4

This is is likely similar to traces you have produced in other languages.

This is the least advanced and worst debugging method, and also most popular.

1. Textual tracer: trace/0

Try it in your Prolog system with:

?- trace, your_goal.

Then painfully step through the code.

This is a sure way to go insane as fast as you can.

2. Graphical tracer

Some Prolog systems provide a graphical tracer.

For example, in SWI-Prolog, try:

?- gtrace, your_goal.

The graphical tracer is a quite complex program and has bugs on its own.

3. Declarative debugging highly recommended

In total, I strongly recommend to avoid tracing in Prolog. The two separate control flows make this language not very suitable to "stepping through". The good news is that this is also not very necessary: Instead, try declarative debugging by reasoning about generalizations and specializations of your programs. This lets you quickly determine the true causes of unintended failure and nontermination.

Invariably, tracing will lead you to think procedurally about your code, and you will have to wrestle with bugs in your code in addition to the bugs in the tracer, while gaining only little insight into the actual problems of your programs.

See for example and for more information.

1
votes

This video gives an example usage of using the graphical debugger in swi prolog. https://www.youtube.com/watch?v=Ap6o_mgbQIY&t=4s Basically, use gtrace to get in trace mode then use space and s and f keys to navigate the trace, r to redo a failing predicate, e to edit code mid trace. a to abort. You can also set spypoints. Using b to break into another level is also useful feature as you can then try out other queries, to think about why your code has a bug with out losing where you are. Sometimes you want to trace, but as Mat says using declarative debugging techniques is good if your code is pure, but that does not work if your code is non pure.