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?
member
只需通过添加一个检查项目是否是第一个元素的成员的子句来扩展正常的递归定义:
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
您还可以使用flatten/2将所有元素置于同一级别,然后使用普通成员:
?- 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.
如果不包含 x:
?- flatten([a,b,[c,d],[e,[f,g],[y,i]]],Xs), member(x,Xs).
false.
通过这种方式,您可以在一个简单的列表中找到该成员。( _ ) -> 单例变量
//Base Case
member(X, [X | _ ]).
member(X, [ _ | T]) :- member(X, T).
通过这种方式,您可以使用简单列表的定义在嵌套列表中找到该成员:
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