views:

318

answers:

3

I don't know what I'm missing here.

I want to add an element if it is in arg1 but not in arg2 and want to remove an element if it is in arg1 but not in arg2.

I'm using an if condition with includes a function that return true if the element is in the arg2 list, false otherwise. Then use built in predicates append and select to add or remove.

I'm getting false to all my objectives searches. I comment and uncomment depending on what predicate I want, add or remove.

includes([],_).
includes([P|Z],S) :-
    memberchk(P,S), includes(Z,S).

addop([],list,res).
addop([P|R],list,res) :-
    includes(P,s0) -> addop(R,list,res) ; append(P,list,res),
    addop(R,list,res).


rem([],list,res).
rem([P|R],list,res) :-
    includes(P,list) -> rem(R,list,res) ; select(P,list,res),
    rem(R,list,res).

Thanks for help.

+1  A: 

Two comments about your code:

  • your includes predicate seems to take a list as first argument, but you seem to use it as if it was an atom from addop and rem.
  • your addop predicate references s0 which is not defined anywhere, so your code does not compile.
Jerome
+1  A: 

list, res and s0 are atoms. Capitalise the first letter of each, to make them variables.

At the moment, your calls to addop and res are probably failing, because there is no matching rule.

Paul Butcher
+1  A: 

Do you really need to use memberchk and includes? If list items are simple then you can use member predicate (which quite often is built-in):

% member(Element, List) -- determines whether Element is a member of list List
member(X, [X|_]).
member(X, [_|T]):- member(X, T).

Using that, addop could be defined as following:

% addop(A, B, R) -- returns items from A which are not in B
% (filters A over B)
addop(A, [], A).
addop([], _, []).
addop([H | T], L, R):- member(H, L), addop(T, L, R). % skip the item
addop([H | T], L, [H | R]) :- addop(T, L, R). % add the item to the result

Add rem could be:

% rem(A, B, R) -- returns items from A which are in B
% (A intersect B)
rem(_, [], []).
rem([], _, []).
rem([H | T], L, [H | R]) :- member(H, L), rem(T, L, R). % add the item to result
rem([_ | T], L, R):- rem(T, L, R).
Regent