views:

184

answers:

2

How to determine whether two list have same element in prolog? If i have two list A and B, i want to know whether they have the same element.

+2  A: 

You need to write a predicate. You'll probably find the prolog builtin member/2 useful.

It's hard to say any more without giving the answer. Just think about it for a bit. You'll get it.

humble coffee
A: 

Let me know if this is what you where looking for:

same(T, Q) :- any(T, Q), !; any(Q, T), !.

any([X|_], [X,_]):- !.
any([X|T], Q) :- member(X, Q), !; any(T, Q), !.

If you consult it:

?- same([1,2,3,4], [3]).
true.

?- same([1,2,3,4], [4]).
true.

?- same([1], [1,4]).
true.

?- same([1,4], [1]).
true.
Juanjo Conti
Yes,this is helpful,thanks a lot.
ccdavid
You don't actually need to write a recursive predicate for this. member already does the job of scanning a list for an item for you.
humble coffee
@humble coffe: could you explain you affirmation?
Juanjo Conti