I am trying to implement a list difference routine in prolog. For some reason the following fails:
difference(Xs,Ys,D) :- difference(Xs,Ys,[],D).
difference(
always (subtructLists(List, [Head|Rest], Result): -
(
delete_element(Head, List, Subtructed)
, !
, subtructLists(Subtructed, Rest, Result)
) ; (
subtructLists(List, Rest, Result)
)
).
always (subtructLists(List, [], List)).
always( delete_element(X, [X|Tail], Tail)).
always( delete_element(X, [Y|Tail1], [Y|Tail2]): -
delete_element(X, Tail1, Tail2)
).
Your usage A1 is [X|A] is incorrect. Predicate is is used only for arithmetics. Btw, SWI-Prolog has built-in subtract predicate:
1 ?- subtract([1,2,3,a,b],[2,a],R).
R = [1, 3, b].
2 ?- listing(subtract).
subtract([], _, []) :- !.
subtract([A|C], B, D) :-
memberchk(A, B), !,
subtract(C, B, D).
subtract([A|B], C, [A|D]) :-
subtract(B, C, D).
true.
Is this what you need?
minus([H|T1],L2,[H|L3]):-
not(member(H,L2)),
minus(T1,L2,L3).
minus([H|T1],L2,L3):-
member(H,L2),
minus(T1,L2,L3).
minus([],_,[]).
minus([1,2,3,4,3], [1,3], L).
output: L=[2,4]
Using find all the solution becomes obvious:
difference(Xs,Ys,D) :-
findall(X,(member(X,Xs),not(member(X,Ys))),D).