Debugging recursion in Prolog - debugging

Here is my knowledge base:
numeral(0).
numeral(succ(X)) :- numeral(X).
Here is my query:
numeral(X).
Here is what SWI Prolog returns in trace mode:
[trace] ?- numeral(X).
Call: (8) numeral(_3806) ? creep
Exit: (8) numeral(0) ? creep
X = 0 ;
Redo: (8) numeral(_3806) ? creep
Call: (9) numeral(_4006) ? creep
Exit: (9) numeral(0) ? creep
Exit: (8) numeral(succ(0)) ? creep
X = succ(0) ;
Redo: (9) numeral(_4006) ? creep
Call: (10) numeral(_4010) ? creep
Exit: (10) numeral(0) ? creep
Exit: (9) numeral(succ(0)) ? creep
Exit: (8) numeral(succ(succ(0))) ? creep
X = succ(succ(0))
I understand how it finds X=0 answer, I do not fully grasp how it obtains: X = succ(succ(0)). I understand that this is correct answer, but I am not sure how Prologs searched for it.
Here is my thinking:
When it prints Call: (9) numeral(_4006) ? creep it tries this rule: numeral(succ(X)) :- numeral(X). And in particular it probably substitutes _4006 = succ(X)
then it checks that it only holds when numeral(X) holds, which Prolog checks against numeral(0), so result is _4006 = succ(0).
Now if we ask for anther solution it again comes back to numeral(_4006), but what does it guess when is calls numeral(_4010). What is branching process here?
Is there way to get more details?
P.S. This is taken from the following link

Prolog searches trough bactracking. There are two ways Prolog can aim to satisfy an numeral(X) call:
with numeral(0) in which case it unifies X with 0; and
with numeral(succ(Y)) :- numeral(Y) in which case it unifies X with succ(Y) and makes a recursive call.
I here used Y since this also creates confusion: the variables in a clause are locally scoped in the sense that an X in a clause, is not the same variable as an X in a call.
Now in case Prolog backtracks and aims to satisfy the predicate with the clause, then this means that X = succ(Y) with Y a variable, but it needs to make an extra call with numeral(Y) as specified in the body.
Again there are two choices:
with numeral(0) in which case it unifies Y with 0; and
with numeral(succ(Z)) :- numeral(Z) in which case it unifies Y with succ(Z) and makes a recursive call.
In case we go for the first one, Y is set to 0, and thus X = succ(Y) hence X = succ(0). In the latter case X = succ(Y), and Y = succ(Z), and we again make a recursive call.
Now in case we again use the first line for numeral(0), this thus means that Z is unified with 0, hence Z = 0, hence Y = succ(0), hence X = succ(succ(0)).

Related

Hide Module/Package from Trace

How do I hide a module or a whole package from tracing.
I have this query, and I want to step through it, but
I am not interested in what CLP(X) does, only at what point something fails in my query.
?- X in 0..5, X in 7..8.
fail.
?- dif(A, 1), A = 1.
fail.
If I run this query in SWI-Prolog it shows me every nifty
detail of the module CLP(X), not only some inlining
related to the constraints but also everything else from CLP(X):
Welcome to SWI-Prolog (threaded, 64 bits, version 8.1.2)
?- trace.
true.
[trace] ?- X in 0..5, X in 7..8.
Call: (9) clpfd:clpfd_in(_2662, 0..5) ? creep
Call: (10) clpfd:fd_variable(_2662) ? creep
Call: (11) var(_2662) ? creep
Exit: (11) var(_2662) ? creep
Call: (11) true ? creep
Exit: (11) true ? creep
[trace] ?- dif(A, 1), A=1.
Call: (9) dif:dif(_3044, 1) ? creep
Exit: (9) dif:dif(_3410{dif = ...}, 1) ? creep
Call: (9) _3410{dif = ...}=1 ? creep
Is there a way to suppress the internals of CLP(X). For
example if I use another Prolog system, I don't see any
internals of the CLP(X) (Preview):
Jekejeke Prolog 3, Development Environment 1.3.6
?- trace.
Yes
?- X in 0..5, X in 7..8.
0 Call X in 0..5 ?
0 Exit X in 0..5 ?
0 Call X in 7..8 ?
0 Fail X in 7..8 ?
No
?- neq(A, 1), A = 1.
0 Call neq(A, 1) ?
0 Exit neq(A, 1) ?
0 Call A = 1 ?
0 Fail A = 1 ?
No
Is there an elegant way to disable a module/package, but nevertheless see top-level calls/exits from the module/packge?
There are various ways to control the debugging process in SWI-Prolog, see http://www.swi-prolog.org/pldoc/man?section=debugging. In this can you can use the skip option, which will "skip to exit port of this call or wake port". The option is activated by pressing s during the trace intead of Enter.
In this case skipping over all calls results in a trace which is very similar to your Jekejeke example (although a bit less nicely formatted):
?- use_module(library(clpfd)).
true.
?- trace.
true.
[trace] ?- X in 0..5, X in 7..8.
Call: (9) clpfd:clpfd_in(_7788, 0..5) ? skip
Exit: (9) clpfd:clpfd_in(_8226{clpfd = ...}, 0..5) ? creep
Call: (9) integer(_8226{clpfd = ...}) ? skip
Fail: (9) integer(_8226{clpfd = ...}) ? creep
Call: (9) clpfd:clpfd_in(_8226{clpfd = ...}, 7..8) ? skip
Fail: (9) clpfd:clpfd_in(_8226{clpfd = ...}, 7..8) ? creep
false.

Difference between two Implementation of even and odd in Prolog

i have two implementation of Prolog , the Function is to decide if the given number is odd or even
the first one works correctly
even1(0).
even1(X) :- X>0 ,X1 is X-1, odd1(X1).
odd1(1).
odd1(X) :- X>1 , X1 is X-1, even1(X1).
even1(2) returns true
but the second one doesnt work correctly
even2(0).
even2(X) :- X>0 , odd2(X-1).
odd2(1).
odd2(X) :- X>1 , even2(X-1).
even2(2) returns false
can anyone explain to me whats is the difference between the two of them ?
Prolog is a relational language, not a functional language. Thus, when you call odd2(X-1), the predicate argument, X-1, is not evaluated as an expression but interpreted as a compound term:
?- functor(X-1, Name, Arity).
Name = (-),
Arity = 2.
You can check what happens when Prolog proves a query by using your system trace functionality:
?- trace.
true.
[trace] ?- even2(2).
Call: (8) even2(2) ? creep
Call: (9) 2>0 ? creep
Exit: (9) 2>0 ? creep
Call: (9) odd2(2-1) ? creep
Call: (10) 2-1>0 ? creep
Exit: (10) 2-1>0 ? creep
Call: (10) even2(2-1-1) ? creep
Call: (11) 2-1-1>0 ? creep
Fail: (11) 2-1-1>0 ? creep
Fail: (10) even2(2-1-1) ? creep
Fail: (9) odd2(2-1) ? creep
Fail: (8) even2(2) ? creep
false.
Note that the expression 2-1-1 evaluates to zero but, being a compound term, the call even2(2-1-1) doesn't unify with your base case for the predicate, even2(0):
?- even2(2-1-1) = even2(0).
false.
?- 2-1-1 = 0.
false.
Therefore, Prolog tries the second clause and the call eventually fails the X>0 check. Note that >/2, by being an arithmetic comparison predicate, it does evaluate its arguments prior to the actual comparison.

Error when defining length in SWI Prolog

I have defined a procedure named length in a file named test.pl:
% Finds the length of a list.
length([], 0).
length([_ | Tail], N) :-
length(Tail, N1),
N is 1 + N1.
When the program is run using SWI-Prolog (prolog test.pl), the following error appears:
ERROR: /home/user/test.pl:2:
No permission to modify static procedure `length/2'
Defined at /usr/lib/swi-prolog/boot/init.pl:3496
ERROR: /home/user/test.pl:3:
No permission to modify static procedure `length/2'
Defined at /usr/lib/swi-prolog/boot/init.pl:3496
I tried changing the name of the procedure from length to mylength, and the error disappears. What does this error mean? Can I define a procedure named length? If not, why can't it be done?
length/2 isn't defined in Prolog, but it's instead part of the shallow interface over native (high efficient) lists implementation. You should use the directive redefine_system_predicate.
For instance, save in a file redef_length.pl
:- redefine_system_predicate(length(?,?)).
% Finds the length of a list.
length([], 0).
length([_ | Tail], N) :-
length(Tail, N1),
N is 1 + N1.
then consult it
?- [test/prolog/redef_length].
true.
?- trace.
true.
[trace] ?- length(A,B).
Call: (8) length(_1476, _1478) ? creep
Exit: (8) length([], 0) ? creep
A = [],
B = 0 ;
Redo: (8) length(_1476, _1478) ? creep
Call: (9) length(_1718, _1738) ? creep
Exit: (9) length([], 0) ? creep
Call: (9) _1478 is 1+0 ? creep
Exit: (9) 1 is 1+0 ? creep
Exit: (8) length([_1716], 1) ? creep
A = [_1716],
B = 1
That's right. length/2 is a built-in predicate: length(?List, ?Int) is True if Int represents the number of elements in List. So the name is already used.

Prolog - infinite loop

I want to check if element is in the middle of list.
I search middle element and next I check if is a member of list, but I get infinite loop.
My predicates:
remove_first([_,H1|T], [H1|T]).
remove_last([_],[]).
remove_last([H|T], [H|T2]) :- remove_last(T, T2).
remove_first_and_last([X],[X]).
remove_first_and_last(In, Out) :-
remove_first(In, Out1),
remove_last(Out1, Out).
middle([X], [X]).
middle(In, X) :-
remove_first_and_last(In, Out),
middle(Out, X).
member(X, [X|_]).
member(X, [_|T]) :- member(X, T).
is_middle(X, In) :-
middle(In, Out),
member(X, Out), !.
And when I call is_middle(1,[2,1,3]) then I get true.
But when I call is_middle(1,[2,2,3]) then I don't get a result. Interpreter don't interrupt the processing.
In a situation as yours, you have two options. Either wade through walls of text of traces as you can see in another answer, or try to reduce first what you have to understand. I prefer the latter for I don't like to read much.
But your major problem is this. You said:
And when I call is_middle(1,[2,1,3]) then I get true.
Yes, Prolog found a solution, but it did not find it once but infinitely many times. Just hit SPACE or ; to see this:
?- is_middle(1,[2,1,3]).
true
; true
; true
; true
; true
; ... .
So, already your first query was problematic. The best way to observe this, is to add false to this query:
?- is_middle(1,[2,1,3]), false.
loops.
Now, let's try to reduce the size of the query. We can narrow it down to:
?- is_middle(1,[1]), false.
loops.
With this we can now look at your program. Before anything else I'll remove the cut. It is misplaced anyway.
To understand what is actually happening, I will narrow down your program by inserting false into it. With these extra goals it is possible to eliminate a lot of unnecessary detail. And still, the remaining program called a failure-slice is of relevance to us, if it is still looping.
remove_first_and_last([X],[X]).
remove_first_and_last(In, Out) :- false,
remove_first(In, Out1),
remove_last(Out1, Out).
middle([X], [X]) :- false.
middle(In, X) :-
remove_first_and_last(In, Out),
middle(Out, X), false.
is_middle(X, In) :-
middle(In, Out), false,
member(X, Out).
Compare this to your original program! Much less reading. To fix the problem you have to fix something in the remaining fragment. I suggest to remove the fact remove_first_and_last([X],[X]). This fact suggests that something is removed, but for this very case, nothing is removed.
For a solution using a dcg directly:
is_middle(E, Es) :-
phrase(middle(E), Es).
middle(E) --> [E].
middle(E) --> [_], middle(E), [_].
That is as short as it can get, but it has a tiny problem: It does not compute the answer determinately. You can see this by looking at the answer:
?- is_middle(1, [2,1,3]).
true
; false.
This ; false is an indication that Prolog was not able to finish the computation determinately. In other words, some space is left. You might be tempted to use a cut. Resist!
If you are really into speed, take the fastest version:
is_middle(X, Xs) :-
Xs = [_|Cs],
middle_el(Cs, Xs, X).
middle_el([], [X|_], X).
middle_el([_,_|Cs], [_|Xs], X) :-
middle_el(Cs, Xs, X).
In case you want #DanielLyons' interpretation which admits even-length lists to have two middle elements, see how easy it is to adopt above grammar definition. Simply add the following two rules:
middle(E) --> [E,_].
middle(E) --> [_,E].
Alternatively, combine all four rules into one:
middle(E) --> [E] | [E,_] | [_,E] | [_], middle(E), [_].
For the fastest solution, things are a bit more complex ...
is_middle_dl(X, Xs) :-
Xs = [_|Cs],
middle_el_dl(Cs, Xs, X).
middle_el_dl([], [X|_], X).
middle_el_dl([_|Cs], Xs, X) :-
middle_el_dl2(Cs, Xs, X).
middle_el_dl2([], [A,B|_], X) :-
( X = A ; X = B ).
middle_el_dl2([_|Cs], [_|Xs], X) :-
middle_el_dl(Cs, Xs, X).
To check it, I use:
?- length(Xs, N), N mod 2 =:= 0, is_middle_dl(X, Xs).
Xs = [X,_A], N = 2
; Xs = [_A,X], N = 2
; Xs = [_A,X,_B,_C], N = 4
; Xs = [_A,_B,X,_C], N = 4
; Xs = [_A,_B,X,_C,_D,_E], N = 6
; Xs = [_A,_B,_C,X,_D,_E], N = 6
; Xs = [_A,_B,_C,X,_D,_E,_F,_G], N = 8
; Xs = [_A,_B,_C,_D,X,_E,_F,_G], N = 8
; Xs = [_A,_B,_C,_D,X,_E,_F,_G,_H,_I], N = 10
; Xs = [_A,_B,_C,_D,_E,X,_F,_G,_H,_I], N = 10
; ... .
Debugging Prolog takes some different skills, so let's take the long road there.
First, let's notice something interesting about your two sample queries. The first one succeeds, and it should; the second one should fail, but instead it loops. This tidbit is a clue: it suggests that we're trying to handle a false case. This is a common mistake among people using Prolog after other languages. In Prolog, it's often enough to be explicit about successful cases and just let failures happen through failed unifications.
The standard tool for debugging Prolog is trace/0. The idea is, you activate trace mode and then run your query, like this:
?- trace, is_middle(1,[2,2,3]).
The trouble with trace/0 is that it can take some effort to understand what's happening with it. Each line starts with one of these four verbs: call, exit, redo, or fail. Then there's a number which indicates the nesting level of the call. The call and redo verbs tell you that you're entering a computation; exit and fail tell you a computation is ceasing and the nesting level is about to decrease. Call/exit are the normal case, fail/redo are what makes Prolog special, the non-determinism. In general, an infinite loop will look like some prefix of meaningful work (or possibly not) followed by an endlessly repeating chunk of output from trace. And we see that here. Prefix:
Call: (8) is_middle(1, [2, 2, 3]) ? creep
Call: (9) middle([2, 2, 3], _G1194) ? creep
Call: (10) remove_first_and_last([2, 2, 3], _G1194) ? creep
Call: (11) remove_first([2, 2, 3], _G1194) ? creep
Exit: (11) remove_first([2, 2, 3], [2, 3]) ? creep
Call: (11) remove_last([2, 3], _G1197) ? creep
Call: (12) remove_last([3], _G1190) ? creep
Exit: (12) remove_last([3], []) ? creep
Exit: (11) remove_last([2, 3], [2]) ? creep
Exit: (10) remove_first_and_last([2, 2, 3], [2]) ? creep
Repeating chunk:
Call: (10) middle([2], _G1200) ? creep
Exit: (10) middle([2], [2]) ? creep
Exit: (9) middle([2, 2, 3], [2]) ? creep
Call: (9) member(1, [2]) ? creep
Call: (10) member(1, []) ? creep
Fail: (10) member(1, []) ? creep
Fail: (9) member(1, [2]) ? creep
Redo: (10) middle([2], _G1200) ? creep
Call: (11) remove_first_and_last([2], _G1200) ? creep
Exit: (11) remove_first_and_last([2], [2]) ? creep
Now you can see it would be much easier to trigger the bad behavior just with this query:
[trace] ?- is_middle(2,[3]).
Call: (7) is_middle(2, [3]) ? creep
Call: (8) middle([3], _G398) ? creep
Exit: (8) middle([3], [3]) ? creep
Call: (8) member(2, [3]) ? creep
Call: (9) member(2, []) ? creep
Fail: (9) member(2, []) ? creep
Fail: (8) member(2, [3]) ? creep
Redo: (8) middle([3], _G398) ? creep
Call: (9) remove_first_and_last([3], _G398) ? creep
Exit: (9) remove_first_and_last([3], [3]) ? creep
Call: (9) middle([3], _G401) ? creep
Exit: (9) middle([3], [3]) ? creep
Exit: (8) middle([3], [3]) ? creep
Call: (8) member(2, [3]) ? creep
Call: (9) member(2, []) ? creep
Fail: (9) member(2, []) ? creep
Fail: (8) member(2, [3]) ? creep
Redo: (9) middle([3], _G401) ? creep
Now it should be clear that the problem has to do with the interplay of middle/2, remove_first_and_last/2 and member/2. Your definition of member/2 is exactly the standard definition so it probably isn't to blame. Now, interestingly, you have middle/2 calling both itself and remove_first_and_last/2. And both middle/2 and remove_first_and_last/2 have an identical clause: m([X], [X]).
This kind of thing is a great generator of infinite recursion, because the first thing middle/2 does in its second clause is exactly what it just tried to do and failed with its own first clause. So it can find itself entering a recursive call in the second clause with exactly the same state it had in an earlier failed call to itself.
The solution is to look at remove_first_and_last/2 and realize that your first clause there does not actually remove the first and last element. Removing the remove_first_and_last([X], [X]) clause fixes the code:
[trace] ?- is_middle(2,[3]).
Call: (7) is_middle(2, [3]) ? creep
Call: (8) middle([3], _G398) ? creep
Exit: (8) middle([3], [3]) ? creep
Call: (8) member(2, [3]) ? creep
Call: (9) member(2, []) ? creep
Fail: (9) member(2, []) ? creep
Fail: (8) member(2, [3]) ? creep
Redo: (8) middle([3], _G398) ? creep
Call: (9) remove_first_and_last([3], _G398) ? creep
Call: (10) remove_first([3], _G398) ? creep
Fail: (10) remove_first([3], _G398) ? creep
Fail: (9) remove_first_and_last([3], _G398) ? creep
Fail: (8) middle([3], _G398) ? creep
Fail: (7) is_middle(2, [3]) ? creep
false.
Both your tests also now work:
?- is_middle(1,[2,1,3]).
true.
?- is_middle(1,[2,2,3]).
false.
I think you added the base case here out of a sense of duty to have one. But the reality is that if you have a list of one element, it should fail to unify with remove_first_and_last/2 under any circumstance. This is very similar to handling an error case explicitly with Prolog, which tends to interfere with the working of the machinery.
Now, one thing that's missing is, how do you want to handle even-length lists? What you have right now won't, with or without my change. Even-length lists don't have a middle element; is that what you intend? I suspect it isn't, because of the appearance of member/2 in is_middle/2.
Comments on is_middle/2
What you have here could be restructured like so:
is_middle(X, In) :- middle(In, [X]).
Usage of member/2 isn't buying you anything because middle/2 can't ever produce a non-singleton list in its second argument. But, if it did, because you had even-length lists, it would be profitable. You could even make this code work that way by adding a third clause to middle/2:
middle([X,Y], [X,Y]).
Now see middle/2 works on even-length lists like so:
?- middle([2,1,3,4], X).
X = [1, 3] ;
false.
Now the cut gets you into trouble though. For instance, 1 and 3 are both is_middle/2:
?- is_middle(1, [2,1,3,4]).
true.
?- is_middle(3, [2,1,3,4]).
true.
Unfortunately though, if you ask for middle elements, you just have 1:
?- is_middle(X, [2,1,3,4]).
X = 1.
What happened to 3? You prevented it from being generated with your cut. I am not sure why the cut is here. I think you must have put it in to try and control the infinite recursion, but it doesn't help you, so get rid of it.
Debugging by random addition of cuts is generally not a great idea. A much better approach is using Ulrich Neumerkel's failure slice approach (see this paper or search the tag for more information).
DCG bonus
You can rephrase remove_first_and_last/2 as a DCG rule:
remove_first_and_last --> remove_first, remove_last.
Pretty cool, huh? :) That's because the kind of input/output threading you're doing in that rule exactly what DCG rules get transformed into.
Summary of changes
remove_first_and_last(In, Out) :-
remove_first(In, Out1),
remove_last(Out1, Out).
middle([X], [X]).
middle([X,Y], [X,Y]).
middle(In, X) :-
remove_first_and_last(In, Out),
middle(Out, X).
is_middle(Item,List) :-
append(Left,[Item|Right],List),
length(Left,X),
length(Right,X).
Complex solutions are bad solutions, my friend.
?- is_middle(X,[1,2,3,4,5]).
X = 3 ;
false.
Fully reversible predicate:
?- is_middle(3,L).
L = [3] ;
L = [_G13, 3, _G19] ;
L = [_G13, _G19, 3, _G25, _G28] ;

Prolog if clause returns false

I am learning Prolog and I have a small question.
I'm working on an example which "builds" a tower.
So I define 3 blocks a, b and c.
The third block c lays on top of a and b -> so it is supported by a and b.
block(a).
block(b).
block(c).
%supported(BLOCK, BY1, BY2)
supported(c,a,b).
level(BLOCK, LEVEL) :-
supported(BLOCK, X, _)
-> (level(X, LEV1), LEVEL is LEV1 + 1)
; LEVEL is 0.
I also have a function to calculate the level of a block. The problem I have is the following:
?- level(X, 0).
false.
?- level(X, 1).
X = c.
Why is it returning false for the level 0 and how can i fix it?
I would like to have a method which returns me a and b for level 0.
consider that
?- level(a,0).
true.
it's evident that when BLOCK is free the supported(BLOCK, X, _) succeeds, forcing the rule on the unintended conjuntion level(X, LEV1), LEVEL is LEV1 + 1, that indeed fails.
To correct the behaviour, bind BLOCK:
level(BLOCK, LEVEL) :-
block(BLOCK),
(supported(BLOCK, X, _) -> level(X, LEV1), LEVEL is LEV1 + 1 ; LEVEL is 0).
One can debug this using trace. (added indentation):
[trace] ?- level(X, 0).
Call: (6) level(_G2697, 0) ? creep
Call: (7) supported(_G2697, _G2771, _G2772) ? creep
Exit: (7) supported(c, a, b) ? creep
Call: (7) level(a, _G2771) ? creep
Call: (8) supported(a, _G2771, _G2772) ? creep
Fail: (8) supported(a, _G2771, _G2772) ? creep
Redo: (7) level(a, _G2771) ? creep
Call: (8) _G2770 is 0 ? creep
Exit: (8) 0 is 0 ? creep
Exit: (7) level(a, 0) ? creep
Call: (7) 0 is 0+1 ? creep
Fail: (7) 0 is 0+1 ? creep
Fail: (6) level(_G2697, 0) ? creep
false.
So what happened?
First you call level(X,0). This predicate calls supported with supported(BLOCK,X,_). There is one answer that unifies: BLOCK=a, X=b and _=c. So that means the if-then-else statement uses the then-part.
In the then-part, it queries level/2 again with level(b,LEV1), now this call results in a call to support(b,LEV1,_). For this call, it can't resolve the call, because there is no support predicate with the first value b. So now we take the else-part. We unify LEV1 is 0, thus LEV1=0 and we return.
In the return part (in the then-part), level(b,0) is the result. Now we unify LEVEL is LEV1+1, LEVEL however was already grounded as 0 and 0+1 is 1. Thus it fails on the top level.
The resolution is probably to make supported finer, and define it as: support/2.
The program reads:
block(a).
block(b).
block(c).
%supported(BLOCK, BY1, BY2)
supported(c,b).
supported(c,a).
supported(b,a).
Now the level predicate reads:
level(B,L) :-
supported(B,C),
level(C,LC),
L is LC+1.
level(_,0).

Resources