Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if all elements of one list are members of another list in Prolog

I'm learning Prolog right now and the recursive thinking is difficult to me.

I have two lists e.g. L1=[1,2,3] and L2=[3,1,2] and I should check if all elements of L1 are contained in L2

So allMembers(L1,L2). should return true and allMembers(L1,[2,3,4]). should return false, because there is no 4 in L1

I thought it would be possible to get the head of the one list and return true if it finds that element in the other list (by splitting it down until the list only contains one item), but I have no idea how to do that in Prolog.

It would be nice if you could help me getting faster on the uptake (?)

I found similar problems here, but couldn't find an answer to my specific problem :/

Edit:
I now have:

isMemberOf(X,[X|_]).
isMemberOf(X,[_|T]):- member(X,T).

which I need to use for any element in L1 to L2

like image 342
Rasalas Avatar asked Dec 18 '22 22:12

Rasalas


1 Answers

Quick solution using de facto standard predicates:

all_from_first_in_second(List1, List2) :-
    forall(member(Element,List1), member(Element,List2)).
like image 194
Paulo Moura Avatar answered Jan 13 '23 14:01

Paulo Moura