member(K,[a,b,c,d])
如果是......
两个人的陈述是什么??
答案 0 :(得分:2)
冲洗并重复:
?- List = [a,b,c,d],member(X,List),member(Y,List).
如果你想要两个不同的元素,那么
?- List = [a,b,c,d],member(X,List),member(Y,List),X \== Y.
然后将其包含在谓词中,如果这就是你所追求的:
two_members(X,Y,List) :-
member(X,List),
member(Y,List),
X \== Y.
答案 1 :(得分:1)
我已经对谓词two_members/3
的预期语义进行了一些不同的解释:
X
中绘制项目Y
和Ls
。Ls
必须至少有两个two_members/3
列表项才能成功。X
至少包含Y
两次,则Ls
和X
可能相等。基于内置谓词select/3
和member/2
,我们定义:
two_members(X,Y,Ls) :-
select(X,Ls,Ls0),
member(Y,Ls0).
让我们运行一些查询!首先,问题中OP建议的查询:
?- two_members(X,Y,[a,b,c,d]).
X = a, Y = b ;
X = a, Y = c ;
X = a, Y = d ;
X = b, Y = a ;
X = b, Y = c ;
X = b, Y = d ;
X = c, Y = a ;
X = c, Y = b ;
X = c, Y = d ;
X = d, Y = a ;
X = d, Y = b ;
X = d, Y = c ;
false.
如果某个项目在Ls
中多次出现怎么办?
?- two_members(X,Y,[a,a,b]).
X = a, Y = a ;
X = a, Y = b ;
X = a, Y = a ; % redundant answer
X = a, Y = b ; % redundant answer
X = b, Y = a ;
X = b, Y = a ; % redundant answer
false.
上述冗余答案怎么样?它们来自哪里,我们可以避免它们吗?
冗余答案来自select/3
和member/3
:
?- select(X,[a,a,b],Xs).
X = a, Xs = [a,b] ;
X = a, Xs = [a,b] ; % redundant answer
X = b, Xs = [a,a] ;
false.
?- member(X,[a,a,b]).
X = a ;
X = a ; % redundant answer
X = b.
为了摆脱这些冗余,我们可以使用
memberd/2
代替member/2
和。{
selectd/3
代替select/3
。让我们再次运行查询:
?- selectd(X,[a,a,b],Xs). X = a, Xs = [a,b] ; X = b, Xs = [a,a] ; false. ?- memberd(X,[a,a,b]). X = a ; X = b ; false.
多余的答案消失了!因此,我们相应地重新定义two_members/3
:
two_members(X,Y,Ls) :- selectd(X,Ls,Ls0), memberd(Y,Ls0).
以上是用于的two_members/3
查询给出了这些多余的答案:
?- two_members(X,Y,[a,a,b]).
X = a, Y = a ;
X = a, Y = b ;
X = b, Y = a ;
false. % all of above redundant answers have gone!