2

The following predicate is remove(L,X,R), where L is a list, X is an element to remove from the list. The code returns the correct list, however it always also returns false afterwards.

I can't find the place where two of the rules can be applied during runtime.

remove([],X,[]) :- !. 
remove([X|T],X,L1) :- remove(T,X,L1). 
remove([H|T],X,[H|L1]) :- \+(X==H), remove(T,X,L1). 

Sample query with expected result:

?- remove([1,2,3,4],3,R).
R = [1, 2, 4] ; 
false.
repeat
  • 18,496
  • 4
  • 54
  • 166
screenshot345
  • 598
  • 3
  • 9
  • 18

2 Answers2

2

If your Prolog system supports , you can preserve by proceeding as follows. Using tfilter/3 and reified inequality predicate dif/3, we can write:

remove(Xs0,E,Xs) :- tfilter(dif(E),Xs0,Xs).

Quick check if it works:

?- tfilter(dif(3),[1,2,3,4],Xs).
Xs = [1,2,4].                     % succeeds deterministically

tfilter/3 and dif/3 are monotone, so we get sound answers, even for general queries:

?- remove([A,B,C],3,Xs).
Xs = [     ],     A=3 ,     B=3 ,     C=3  ;
Xs = [    C],     A=3 ,     B=3 , dif(C,3) ;
Xs = [  B  ],     A=3 , dif(B,3),     C=3  ;
Xs = [  B,C],     A=3 , dif(B,3), dif(C,3) ;
Xs = [A    ], dif(A,3),     B=3 ,     C=3  ;
Xs = [A,  C], dif(A,3),     B=3 , dif(C,3) ;
Xs = [A,B  ], dif(A,3), dif(B,3),     C=3  ;
Xs = [A,B,C], dif(A,3), dif(B,3), dif(C,3) ;
false.
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166
1

http://www.cs.bris.ac.uk/Teaching/Resources/COMS30106/labs/tracer.html - SWI-prolog has tracing/debugging mode. In my opinion, cmd-line debugger is better than the visual one.

EDIT:

remove([],X,[]) :- !. 
remove([X|T],X,L1) :- !, remove(T,X,L1).          <-- cut was added
remove([H|T],X,[H|L1]) :- remove(T,X,L1).         <-- condition was deleted

The above code should be allright. No warranties though.

MartyIX
  • 27,828
  • 29
  • 136
  • 207
  • Thank you - I'll use it to debug and find my problem. – screenshot345 Apr 01 '10 at 18:58
  • Well, you get the result as you wrote above because: when the prolog recurses to the element 3 it has two choices: use second predicate or use third predicate. Usage of the second predicate leads to the result R = [1, 2, 4] ; ... which is what you want. But usage of the third predicate (this predicate is used when you want more results from SWI-prolog) leads to the false result - why? Because the unification on the head of predicate is used (and therefore H and X has the same value 3) and then the condition \+(X==H) is checked which fails => therefore result "false.". – MartyIX Apr 01 '10 at 20:00
  • Thank you! Thats excellent! I wasn't aware that you are able to cut on a line with other calls! I have tested your code and it works fabulously. – screenshot345 Apr 02 '10 at 22:59