Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an element exists in a list of lists?

I want to find if a given element exists in a list of lists. I am only getting true if the element exists somewhere is the first list of lists.

Any advice?

memberlist(X,[[X|T1]|T2]).
memberlist(X,[[H|T1]|T2]) :-
  memberlist(X,[T1|T2]).
like image 456
Alator Avatar asked Apr 14 '17 15:04

Alator


Video Answer


1 Answers

memberlists(X, Xss) :-
   member(Xs, Xss),
   member(X, Xs).

Similar to member/2, this produces many redundant answers like:

?- memberlists(X, [[a,a],[a],[a]]).
   X = a
;  X = a  % redundant
;  X = a  % redundant
;  X = a. % redundant

Alternatively, you might want to use memberd/2 in place of member/2.

memberlists2(X, Xss) :-
   memberd(Xs, Xss),
   memberd(X, Xs).

?- memberlists2(X, [[a,a],[a],[a]]).
   X = a
;  X = a   % redundant
;  false.

This is much better, but still does not remove all redundant answers.

For a solution that removes all such redundancies a bounty has been set.

like image 154
false Avatar answered Oct 16 '22 19:10

false