Prolog, List of lists contains another list exactly

610 Views Asked by At

What I basically want to achieve is, that given a list of lists A, I want a predicate that checks if the elements of a list B are exactly contained in list A.

So for example:

A = [[1,2],[3,4],[5],[]] B = [1,2,3,4,5]

and

A = [[1,2],[3,4],[5],[]] B = [2,5,3,4,1]

Would result to true, but

A = [[1,2],[3,4],[5],[]] B = [1,2,3,4]

and

A = [[1,2],[3,4],[5],[]] B = [1,2,3,4,5,6]

would both result to false.

is this possible in prolog?

Exactly means: Order doesn't matter, it just has to contain all the elements. Also, imagine that the B list doesn't contain duplicates. So if A would contain duplicates, we should get false as a result.

1

There are 1 best solutions below

0
On BEST ANSWER

The trivial answer:

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

?- flatten([[1,2],[3,4],[5],[]], [1,2,3,4]).
false.

?- flatten([[1,2],[3,4],[5],[]], [1,2,3,4,5,6]).
false.

Or,

foo(A, B) :- % because I don't know how to call it
    flatten(A, B).

If you are talking about sets:

bar(A, B) :-
    flatten(A, A_flat),
    sort(A_flat, A_sorted),
    sort(B, A_sorted).

You can use msort/2 if you don't want to remove duplicates.

If the question is, "how do I implement flatten/2", you can find several answers on SO.