0

我正在制作一个 prolog 知识库来实现几何规则。在测试矩形是否有直角时,我找到了两个答案。

?- rect_tri(triangle(line(point(0,0),point(0,1)),line(point(0,1),point(1,0)),line(point(1,0),point(0,0)))).
true ;
false.

这里是知识库:

point(X,Y).
line(X,Y) :- X = point(A,B), Y = point(C,D), not(X = Y). 
len(X,R) :- X = line(P,Q), P = point(A,B), Q = point(C,D), not(P = Q), 
    R is sqrt((A - C) * (A - C) + (B - D) * (B - D)).
triangle(X,Y,Z) :- X = point(A,B), Y = point(C,D), Z = point(E,F),
    not(X = Y), not(X = Z), not(Y = Z), 
    L1 = line(X,Y), L2 = line(X,Z), L3 = line(Y,Z),
    len(L1,G), len(L2,H), len(L3,I),
    G + H > I, G + I > H, H + I > G.
triangle(X,Y,Z) :- X = line(A,B), Y = line(B,C), line(A,C),
    len(X,G), len(Y,H), len(Z,I),
    G + H > I, G + I > H, H + I > G.
rect_tri(X) :- X = triangle(A,B,C), len(A,G), len(B,H), len(C,I),
    (G is sqrt(H * H + I * I); 
        H is sqrt(G * G + I * I); 
        I is sqrt(H * H + G * G)).

跟踪时,我发现当 prolog 到达 line 时答案为 true H is sqrt(G * G + I * I),而在评估最后一行时为 false。

我不希望发生最后一次评估,因为我希望它在找到 true 时退出。

4

1 回答 1

2

丹尼尔评论可能显示了解决您的问题的最明智的方法。一些其他的选择...

在现代编译器中有 if/then/else 构造:

rect_tri(X) :- X = triangle(A,B,C), len(A,G), len(B,H), len(C,I),
    (  G is sqrt(H * H + I * I)
    -> true
    ;  H is sqrt(G * G + I * I)
    -> true
    ;  I is sqrt(H * H + G * G)
    ).

你也可以使用cuts(老式的方式,在这里更具可读性):

rect_tri(X) :- X = triangle(A,B,C), len(A,G), len(B,H), len(C,I),
    (  G is sqrt(H * H + I * I), !
    ;  H is sqrt(G * G + I * I), !
    ;  I is sqrt(H * H + G * G)
    ).
于 2013-07-10T07:24:57.490 回答