Prolog语句语法

时间:2009-12-23 02:37:59

标签: prolog

member(K,[a,b,c,d])如果是......

之一

两个人的陈述是什么??

2 个答案:

答案 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绘制项目YLs
  • Ls必须至少有两个two_members/3列表项才能成功。
  • 如果X至少包含Y两次,则
  • LsX可能相等。

基于内置谓词select/3member/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/3member/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!