Prolog:指示OR规则中哪个谓词为真



在SWI-Prolog中,我有一些事实和由这些事实组成的规则,就像这样:

father(a, b).
mother(a, c).
parent(A, X) :- father(A, X); mother(A, X).

这一切都很好,当我查询时,我得到这个:

?- parent(a, X).
X = b ;
X = c.

我想知道是否有一种方法来编写一个规则,表明哪个谓词为每个结果为真,就像这样:

?- parent(a, X).
X = b, R = father ;
X = c, R = mother.

谢谢!

术语是对数据进行分类的一种简单方法,作为添加另一个变量的替代方法,例如:

father(a, b).
mother(a, c).
parent(father(F), C) :- father(F, C).
parent(mother(M), C) :- mother(M, C).

结果swi-prolog:

?- parent(P, C).
P = father(a),
C = b ;
P = mother(a),
C = c.

这里父级通过创建相应的术语保留了父/母级规则的分类。

您还可以更改谓词来指示两个人是否相关,以及如何相关:

related(A, B, father(A,B)) :- father(A,B).
related(A, B, mother(A,B)) :- mother(A,B).

也许可以添加一个更一般的规则来指示两个人之间是否存在关系链。

related(A, B, (R1,R2)) :- related(A,Z,R1), related(Z,B,R2).

如果你不想重写你的程序,你可以跟踪它。这个答案并不比其他答案好,它只是一种不同的方法。

如果我跟踪mother/2father/2,只有exit端口,所以我只看到成功:

?- trace(mother/2, +exit), trace(father/2, +exit).
%         mother/2: [exit]
%         father/2: [exit]
true.
?- parent(a, X).
T [11] Exit: father(a, b)
X = b ;
T [11] Exit: mother(a, c)
X = c.

谓词记录在这里:https://www.swi-prolog.org/pldoc/man?section=debugger

这里有一个非常好的教程式的概述:https://www.swi-prolog.org/pldoc/man?section=debugoverview

我特别用这一节来回答你的问题:https://www.swi-prolog.org/pldoc/man?section=trace-mode-vs-point

最新更新