bpavlov
bpavlov

Reputation: 1090

Prolog member of List of List

I want to define a predicat p(X), where X is list of lists. p(X) is true, if in X there is only one element Y, that X and Y have no common elements.

This is not homework. This is a example problem for my exam. Thank you.

Upvotes: 0

Views: 2707

Answers (1)

Will Ness
Will Ness

Reputation: 71065

Write it down:

p(X):-    %//  "define a predicate p(X), where X is list of lists, such that 
          %//   p(X) is true if in X there is only one element Y, 

  % findall( Y, (member(Y,X), ........ ), [_])

          %//   such that X and Y have no common elements".

    findall( Y, (member(Y,X), \+ have_common_element(X,Y) ), [_]).

have_common_element(A,B):- member(X,A), memberchk(X,B).

Now,

8 ?- p([[1,[2]],[2],[3]]). %// both [2] and [3] have no common elts w/ X
false.

9 ?- p([[1,[2]],[2]]).     %// [1,[2]] has one common elt w/ X, viz. [2]
true.

Prolog lists are heterogeneous. An element might be a list as well. And its element too.

Upvotes: 1

Related Questions