Reputation: 1299
I want to check if x
is a member of a nested list, so that
member(x,[a,b,[c,d],[e,[f,g],[x,i]]])
returns True
, and False
if there is no x
. Is this possible somehow?
Upvotes: 3
Views: 5713
Reputation: 337
By this you find the member in a simple list. ( _ ) -> Singleton Variable
//Base Case
member(X, [X | _ ]).
member(X, [ _ | T]) :- member(X, T).
By this you find the member in a nested list using the defination of a simple list:
nestedListMember(X, [H | T]) :-
member(X,H);
nestedListMember(X,T). %Recursive call looking in the tail
nestedListMember(X,[T]) :-
nestedListMember(X,T). %You look for all the subsequent cases
Upvotes: 0
Reputation: 4998
You can also use flatten/2 to get all elements onto the same level and then use ordinary member:
?- flatten([a,b,[c,d],[e,[f,g],[x,i]]],Xs), member(x,Xs).
Xs = [a, b, c, d, e, f, g, x, i] ;
false.
and if x is not contained:
?- flatten([a,b,[c,d],[e,[f,g],[y,i]]],Xs), member(x,Xs).
false.
Upvotes: 2
Reputation: 5149
Simply expand the normal recursive member
definition by adding a clause that checks if the item is a member of the first element:
member(X, [X|_]). %X is first element
member(X, [L|_]) :- member(X, L). %X is member of first element
member(X, [_|T]) :- member(X, T). %X is member of tail
Upvotes: 6