在Prolog中,我如何定义并查询一个镜像关系和一个非对称关系?

编程语言 2026-07-11

我正在尝试用Prolog查询一个简单的“左”和“右”的关系,以及它们之间的不对称关系。

你的左边是我的右边,我的右边是你的左边。

我在尝试对这个关系进行镜像并查询镜像结果。

知识库里只有一条规则

at(right, sam, fred).

我想推断出Fred的 left等于Sam。

这是我现在的写法:

at(right, sam, fred).


wat(left, X, Y) :-
    at(right, Y, X);
    at(left, X, Y).
wat(right, X, Y) :-
    at(left, Y, X);
    at(right, X, Y).

接着我对其进行查询

wat(N, X, Y).

这会给出两个结果,这是我所预期的。

X = left,
Y = fred,
Z = sam
X = right,
Y = sam,
Z = fred

这种查询有没有一个专门的名称?我想推断出所有的镜像映射——可能不仅仅是左和右。 我不想把它们全部定义在我的知识库里。

有没有更好的方式来表示这个查询?

解决方案

可以把它写得更抽象一点,以提高灵活性:

plane_side_other(horizontal, left, right).
plane_side_other(horizontal, right, left).

% Example of further plane possibilities
plane_side_other(vertical, above, below).
plane_side_other(vertical, below, above).

% Data
at(horizontal, right, sam, fred).

at_side(Plane, Side, X, Y) :-
    (   at(Plane, Side, X, Y)
    ;   plane_side_other(Plane, Side, OtherSide),
        at(Plane, OtherSide, Y, X)
    ).

在swi-prolog中的结果是:

?- at_side(P, S, X, Y).
P = horizontal,
S = right,
X = sam,
Y = fred ;
P = horizontal,
S = left,
X = fred,
Y = sam ;
false.

我认为这类关系并没有特别的名称,它只是互为相反的关系。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章