3

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?

4

3 回答 3

6

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
于 2013-11-02T23:40:05.427 回答
2

您还可以使用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.
于 2013-11-03T22:49:08.607 回答
0

通过这种方式,您可以在一个简单的列表中找到该成员。( _ ) -> 单例变量

//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
于 2016-03-05T19:48:43.473 回答