prolog上不需要的评估

时间:2013-07-10 05:35:46

标签: prolog

我正在制作一个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.

这是kwnoledge基地:

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命中行H is sqrt(G * G + I * I)时答案为true,而在评估最后一行时为false。

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

1 个答案:

答案 0 :(得分:2)

Daniel评论可能会显示解决问题的最明智方法。其他一些选择......

在现代编译器中有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)
    ).

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

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)
    ).