Reputation: 55
Pretty new to Prolog. I'm trying to give two lists and have the difference of the two returned to me. The second list can have bound variables and unbound variables in it. I've tried tracing this and it recurses all the way through and gives me a correct list in NewL, but then on the way back it negates all the deletes I've made. What is going wrong ? Thanks for the help!
% Find difference between two lists, return result in Difference
difference(List,[H|T],Difference) :- % When H is unbound var, use Tail
var(H),!,difference(List,T,Difference),!.
difference(List,[H|T],Difference) :- % When H is bound var, remove from List.
subtract(List,[H],NewL),
difference(NewL,T,Difference),!.
Upvotes: 1
Views: 2930
Reputation: 60014
Assuming that subtract/3 comes from SWI-Prolog library, and thus is correct, you are left with just one possibility: you forgot to declare the base case on the second argument, that drives the recursion.
And take in account the comment from @mog, cuts should be used just when required. Of course, to decide when are required can be difficult...
Upvotes: 3