0

我已经开始学习 Prolog,我想用 findall/3 获取玩家的对手列表。在概括中,我只想将实际上是玩家的对手添加到列表中,除了我自己要求的玩家。我该如何制定这个例外?我知道否定是失败的概念,但我不确定我是否以及如何在这里需要它。

player(irina).
player(anton).
player(michael).

opponent(irina, anton).
opponent(irina, maria).
opponent(irina, michael).

% Only opponents who are also players should be added to the list, 
% except the player of interest itself 
opponent(X, Y) :- X \= Y, player(Y).

% the query
?- findall(O, opponent(irina,O) , OpponentList).

% the result
% only the first three results from the facts, 
% the results from the rule, a second entry of
% anton and michael are missing.
OpponentList = [anton, maria, michael].

我实际上预计,该决议将按如下方式工作:

opponent(irina, irina) :- irina \= irina, player(irina).
%                              false          true
%                                      false
% false, hence not added to the list

opponent(irina, anton) :- irina \= anton, player(anton).
%                              true          true
%                                     true
% true, hence added to the list

我错过了什么?提前谢谢了!

4

1 回答 1

0

代码:

player(irina).
player(anton).
player(michael).

opponent(irina, anton).
opponent(irina, maria).
opponent(irina, michael).

opponent(X, Y) :- 
   format("Called with X = ~q, Y = ~q\n",[X,Y]),
   X \= Y,     % this will fail if Y is still fresh because X and Y can be unified!
   player(Y).

opponent_mod(X, Y) :-
   format("Called with X = ~q, Y = ~q\n",[X,Y]),
   player(Y),  % this will set Y to various players  
   X \= Y.     % the test for un-unifiability of two set vars may or may not succeed 

% query helpfully as code:

q(Who,OpponentList) :- findall(O, opponent(Who,O) , OpponentList).

q_mod(Who,OpponentList) :- findall(O, opponent_mod(Who,O) , OpponentList).

% even better

q_mod_set(Who,OpponentList) :- setof(O, opponent_mod(Who,O) , OpponentList).

运行:

不期望:

?- q(irina,X).
Called with X = irina, Y = _19654
X = [anton, maria, michael].

预期的:

?- q_mod(irina,X).
Called with X = irina, Y = _20568
X = [anton, michael].

Who那么在使用=的“意外”情况下会发生什么irina

  • findall/3尝试收集所有值 Y 使得opponent(Who,O)
  • 它通过 事实anton发现mariamichal
    • opponent(irina, anton).
    • opponent(irina, maria).
    • opponent(irina, michael).
  • 它还尝试opponent(X, Y) :- ...使用X=的规则irina(仅一次)。但是测试X \= Y 失败了,因为X已被限制为irinaY仍然是新鲜的(完全不受限制)。这意味着如果尝试统一X并且Y可以成功(这是正在测试的内容,=并不意味着“不相等”)。X \= Y在这个计算点上也是错误的。如果您X \= Y在 之后移动player(Y)Y则将被限制为从player/1事实中获取的任何内容,这将简化为 和 的值的实际X比较Y
于 2020-04-14T15:12:14.210 回答