user3057088
user3057088

Reputation: 1

prolog program : compares two lists' items and return a list of unique element that are on List1

This program compares two lists' items and returns a list with items that are members of first list and are not members of second list. For example: list1=[a,b,d], list2=[r,a,f,b] ----> result =[a,b].

go:- comp([y,h,b],[b,t],R),!.

comp([],_,_) :- !.
comp(_,[],_) :- !.
comp([H|T],B,_) :- memberchk(H,B),comp(T,B,_); comp(T,B,R),write([H]).

current result is [h][y]

result I need should be [h,y]

Upvotes: 0

Views: 315

Answers (1)

lurker
lurker

Reputation: 58324

Your request is for a predicate which returns a list with items that are members of first list and are not members of second list. But your example:

list1=[a,b,d], list2=[r,a,f,b] ----> result =[a,b]

Is the result of returns a list with members that are in both lists (intersection). I'm assuming you want what you requested, not what your example shows.

In your original, you had:

comp(_, [], _).

Which would not give a correct result if you queried, say, comp([a], [], X) since you're using the "don't care" term, _. It's an improper expression of what you probably intended, which is comp(L, [], L) (a list is itself if you exclude elements of an empty list from it). In addition, none of your original clauses instantiates a result (all of them have the "don't care" _ in that position).

A corrected version might look like this:

comp([], _, []).
comp(L, [], L).
comp([H|T], S, R) :-
    (   memberchk(H, S)
    ->  comp(T, S, R)
    ;   R = [H|RT],
        comp(T, S, RT)
    ).

?- comp([y,h,b],[b,t],R).
R = [y, h] ;
false.

?-

Note that the "false" response after typing ; means there are no additional solutions.

Upvotes: 2

Related Questions