0
votes

I want to write a prolog program that checks if a list is included in other list.
Multiple elements matter
This is what I wrote but it fails for the input - inclusion([a,b,b,d],[a,b,b,c,c,d,d]).
This should return true. other examples - inclusion([a, b, b, b, d], [a, b, b, c, c, d, d])
should return false.

 inclusion([],_).
    inclusion([X|L],Set):-
    member(X,Set),delete(Set,X,Set2), inclusion(L,Set2).

Above is the code that I wrote. The logic was check if the first element is in Set.
Then delete that element from the set and check if the remaining list is in the Set.
But this doesn't seem to work

2

2 Answers

0
votes

This predicate does not work with entries in the first list that appear multiple times, because delete removes all appearances of Set. Use select to remove only the first element that matches:

inclusion([],_).
inclusion([X|L],Set):-
   member(X,Set),select(X, Set, Set2), inclusion(L,Set2).

Gives you:

?- inclusion([a,b,b,d],[a,b,b,c,c,d,d]).
true .

?- inclusion([a,b,b,b,d],[a,b,b,c,c,d,d]).
false.
0
votes
inclus([],[]).
inclus([],[_|_]).
inclus([H1|T1],[H1|T2]) :- inclus(T1,T2).
inclus([H1|T1],[H2|T2]) :- \=(H1,H2),inclus([H1|T1],T2).

Note: the other answer defining the inclusion/3predicate will return true for the following goal:

?- inclusion([b, c, a],[a,b,c]).
true

I dont think this is what you want.