prolog比较段落

时间:2014-03-22 17:28:22

标签: prolog

triangle_area(triangle(point(X1,Y1),point(X2,Y2),H),S):-
M1 is ((X1 - X2)*(X1 - X2)),
N1 is ((Y1 - Y2)*(Y1 - Y2)),
O1 is (M1 + N1),
R1 is (sqrt(O1)),
S is (H*R1).

compare_tri(triangle(point(X1,Y1),point(X2,Y2),H1), triangle(point(X3,Y3),point(X4,Y4),H2)):-
    triangle_area(triangle(point(X1,Y1), point(X2,Y2), H1), S1),
    triangle_area(triangle(point(X3,Y3), point(X4,Y4), H2), S2),
    (   (S1 < S2) -> (S1 is 2), (S2 is 1)
    ;   (S2 is 1), (S1 is 2)),
    write('Triangle '),
    write(S1),
    write(' is bigger than Triangle'),
    write(S2),
    write('.').

compare_tri(triangle(point(0,0),point(2,0),4),triangle(point(0,0),point(3,0),3).

我预计&#39; Triangle 2比Triangle 1大。&#39;

但它没有用。

它只是这样告诉我。

ERROR: Syntax error: Operator expected
ERROR: compare_tri(triangle(point(0,0),point(2,0),4),triangle(point(0,0),point(3,0),3) 
ERROR: ** here **
ERROR: . 

有什么问题?

2 个答案:

答案 0 :(得分:1)

第一个问题是您错过了查询的近括号。

?- compare_tri(triangle(point(0,0),point(2,0),4),triangle(point(0,0),point(3,0),3)).

第二个是你分配给S1和S2,它们已经绑定到该区域。这是一个更正:

compare_tri(triangle(point(X1,Y1),point(X2,Y2),H1),triangle(point(X3,Y3),point(X4,Y4),H2)):-
    triangle_area(triangle(point(X1,Y1),point(X2,Y2),H1),S1),
    triangle_area(triangle(point(X3,Y3),point(X4,Y4),H2),S2),
    ( (S1<S2) -> (T1,T2) = (2,1) ; (T1,T2) = (1,2) ),
    write('Triangle '),
    write(T1),
    write(' is bigger than Triangle'),
    write(T2),
    write('.').

答案 1 :(得分:0)

如果你把事情分解成更小的碎片,它就会更容易理解,以及测试和调试事物并找出问题,如下所示:

triangle_area( triangle(P1,P2,H) , S ) :-
  distance(P1,P2,B) ,
  A is B*H/2.0
  .

distance(point(X1,Y1),point(X2,Y2),L) :-
  Dx is X2-X1 ,
  Dy is Y2-Y1 ,
  Dx2 is Dx*Dx ,
  Dy2 is Dy*Dy ,
  L is sqrt(Dx2+Dy2)
  .

compare_tri( T1, T2 ) :-
  triangle_area(T1, Area1),
  triangle_area(T2, Area2),
  compare(Op,Area1,Area2) ,
  log_results( Op, T1, T2 )
  .

log_results( '>',T1,T2 ) :-
  write(T1),
  write(' is larger than '),
  write(T2),
  nl
  .
log_results( '<',T1,T2 ) :-
  write(T2),
  write(' is larger than '),
  write(T1),
  nl
  .
log_results( '=',T1,T2 ) :-
  write(T1),
  write(' is the same size as '),
  write(T2),
  nl
  .