Prolog list difference routine
Asked Answered
V

4

8

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([],_,A,D) :- D is A, !.
difference([X|Xs],Ys,A,D) :-
  not(member(X,Ys)),
  A1 is [X|A],
  difference(Xs,Ys,A1,D).

When trying:

?- difference([1,2],[],D).

I get this error:

ERROR: '.'/2: Type error: `[]' expected, found `1' ("x" must hold one character)
^  Exception: (10) _L161 is [2|1] ? 
Valma answered 6/10, 2009 at 1:16 Comment(0)
W
10

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?

Whydah answered 6/10, 2009 at 12:52 Comment(0)
F
3
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]
Flagellum answered 8/7, 2011 at 18:41 Comment(0)
V
2

Using find all the solution becomes obvious:

difference(Xs,Ys,D) :- 
  findall(X,(member(X,Xs),not(member(X,Ys))),D).
Valma answered 6/10, 2009 at 2:52 Comment(0)
S
2
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)
).
Seldan answered 13/12, 2012 at 17:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.