[英]Prolog order of query rules
Prolog Question: Just started learning prolog and this was on one of the practice quizzes we were given. 序言问题:刚开始学习序言,这是我们得到的一项实践测验。
avenger(thor).
avenger(captainAmerica).
sibling(thor,loki).
asgardian(thor).
asgardian(X) :- sibling(Y,X),asgardian(Y).
train1(X,Y) :- avenger(X),!,avenger(Y).
train2(X,Y) :- avenger(X),X\=Y,avenger(Y).
train2(A, captainAmerica). %returns A=thor.
train2(captainAmerica, A). %returns false.
My question is about the second query. 我的问题是关于第二个查询。 Why wouldn't this return A=thor. 为什么不返回A = thor。 ? ? I messed around a bit and if i change train2 to 我有点乱了,如果我将train2更改为
train2(X,Y) :- avenger(X),avenger(Y),X\=Y.
when i run the second query I get 当我运行第二个查询时
A=thor.
A quick explanation of why the order of the rules in the query matters here would be awesome. 快速解释一下为什么查询中规则的顺序如此重要的原因。 Thanks. 谢谢。
\\=
is a weird predicate... It says, "if the unification of the two arguments succeeds, fail; if the unification fails, succeed". \\=
是一个奇怪的谓词……它说:“如果两个参数的统一成功,则失败;如果统一失败,则成功”。 So, as the unification of a free variable with an atom will always succeed, it fails. 因此,由于自由变量与原子的统一总是成功的,所以失败了。
Once the Y
has been unified with thor
, the unification of captainAmerica
with thor
fails, so the X \\= Y
succeeds. 一旦Y
与thor
统一,则captainAmerica
与thor
的统一失败,因此X \\= Y
成功。
Anyway, you should not use \\=
in this context. 无论如何,在这种情况下,您不应使用\\=
。 Instead, use dif/2
. 而是使用dif/2
。 Try messing around with a predicate defined as: 尝试弄乱定义为的谓词:
train3(X, Y) :-
dif(X, Y),
avenger(X),
avenger(Y).
Better than the other two in several ways. 在几个方面都比其他两个更好。 You can search SO for other questions with dif/2
. 您可以使用dif/2
搜索其他问题。
The \\=/2
standard predicate is true when its arguments do not unify. 当其参数不统一时, \\=/2
标准谓词为true。 Thus, it requires both arguments to be bound (ie not variables) to be meaningful. 因此,它要求绑定两个参数(即不是变量)才有意义。 Your solution: 您的解决方案:
train2(X,Y) :- avenger(X), avenger(Y), X \= Y.
is correct as the two proceeding calls to the avenger/1
predicate ensure that both X
and Y
will be sufficiently instantiated before the call to the \\=/2
predicate. 是正确的,因为对avenger/1
谓词的两个进行中的调用确保在对\\=/2
谓词的调用之前, X
和Y
都将被充分实例化。
As Boris explained in his answer, the alternative of using the dif/2
predicate, have the virtue of making goal order in the clause above irrelevant. 正如鲍里斯(Boris)在回答中所解释的那样,使用dif/2
谓词的替代方法具有使上述条款中的目标顺序无关紧要的优点。 There's a caveat, however. 但是,有一个警告。 The dif/2
predicate is not a standard predicate and not all Prolog implementations provide it. dif/2
谓词不是标准谓词,并非所有Prolog实现都提供它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.