5

I'm trying to write a code in Prolog to count the distance between two points but when I tried to execute it , it told me that out of local stack any body know what that means and how i can solve it this my code by the way:

point(a,5,2).
point(b,4,0).
point(c,2,3).
point(d,5,2).

distance(N1,N2,D) :-
    distance(point(N1,X1,Y2),point(N2,X2,Y2),Z),
    Z=sqrt(((X1-X2)*(X1-X2))+((Y1-Y2)*(Y1-Y2))).

line(N1,N2,D) :-
    distance(N1,N2,Z).

tangent(X,Y,M) :- 
    tangent(point(N1,X1,Y2),point(N2,X2,Y2),M),
    M=(Y1-Y2)/(X1-X2).
repeat
  • 18,496
  • 4
  • 54
  • 166
hamza yaghi
  • 51
  • 1
  • 2

2 Answers2

3

You are defining distance in terms of distance. Once there's a query for distance, the computer will call distance, which will again call distance, and so forth. This is known as an infinite recursion.

See also this SO question.

You should change your code so that the right hand side of

distance(N1,N2,D):-distance(point(N1,X1,Y2),point(N2,X2,Y2),Z)

does not always refer to the left hand side.

Community
  • 1
  • 1
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
2

I tried:

distance(N1,N2,D) :- point(N1,X1,Y1), 
                     point(N2,X2,Y2),
                     D is sqrt((X2-X1)^2 + (Y2-Y1)^2).

ex.

?- distance(a,b,D).
D = 2.23606797749979.
guest
  • 21
  • 1