只为家谱中的兄弟姐妹获得一个解决方案
Get only one solution for sibling pairs in family tree
我有以下 Prolog 代码,修改自维基百科:
mother_child(trude, sally).
father_child(tom, sally).
father_child(tom, erica).
father_child(mike, tom).
different(X, Y) :- X \== Y.
sibling(X, Y) :- parent_child(Z, X), parent_child(Z, Y), different(X, Y).
parent_child(X, Y) :- father_child(X, Y).
parent_child(X, Y) :- mother_child(X, Y).
我得到以下信息:
?- sibling(X, Y).
X = sally,
Y = erica ;
X = erica,
Y = sally ;
false.
是否可以修改我的代码,使 ?- sibling(X, Y)
变为 return only: X = sally, y = erica ; false.
?也就是说,我想消除 X = Y 和 Y = X(相反)的实例。
@lurker 的评论说明了一切。问问自己查询在问什么:
- 是否有一对 X, Y 使得:
- X 有 parent Z:
- Z当爹了
- Z是妈妈
- Y 有 parent Z:
- Z当爹了
- Z是妈妈
- X 和 Y 不一样
在你现在的数据库中,一个child最多可以有一个妈妈和一个爸爸,所以parent_child/2
的两个子句恰好对于一个child是互斥的。
但是您在 sibling/2
中有 parent_child/2
两次 的子目标,因此对于每对兄弟姐妹,您可以 任一个第一个中的两个,然后是第二个中的另一个,因此每对都有两个证明。说 X @< Y
而不是 X \== Y
将确保只有 X 和 Y 的两种可能组合中的一种导致成功证明。
我有以下 Prolog 代码,修改自维基百科:
mother_child(trude, sally).
father_child(tom, sally).
father_child(tom, erica).
father_child(mike, tom).
different(X, Y) :- X \== Y.
sibling(X, Y) :- parent_child(Z, X), parent_child(Z, Y), different(X, Y).
parent_child(X, Y) :- father_child(X, Y).
parent_child(X, Y) :- mother_child(X, Y).
我得到以下信息:
?- sibling(X, Y).
X = sally,
Y = erica ;
X = erica,
Y = sally ;
false.
是否可以修改我的代码,使 ?- sibling(X, Y)
变为 return only: X = sally, y = erica ; false.
?也就是说,我想消除 X = Y 和 Y = X(相反)的实例。
@lurker 的评论说明了一切。问问自己查询在问什么:
- 是否有一对 X, Y 使得:
- X 有 parent Z:
- Z当爹了
- Z是妈妈
- Y 有 parent Z:
- Z当爹了
- Z是妈妈
- X 和 Y 不一样
- X 有 parent Z:
在你现在的数据库中,一个child最多可以有一个妈妈和一个爸爸,所以parent_child/2
的两个子句恰好对于一个child是互斥的。
但是您在 sibling/2
中有 parent_child/2
两次 的子目标,因此对于每对兄弟姐妹,您可以 任一个第一个中的两个,然后是第二个中的另一个,因此每对都有两个证明。说 X @< Y
而不是 X \== Y
将确保只有 X 和 Y 的两种可能组合中的一种导致成功证明。