Search code examples
prologcoordinatespredicatesqrtpythagorean

Pythagorean theorem for calculating distance between two points. Prolog


We all know that the Pythagorean theorem formula is: a2 + b2 = c2. I wanted to implement this formula, for calculating the distance between two points. This is my data of the coordinates of the cities (in km):

city(amsterdam, 121.813/487.362).
city(breda, 112.095/398.291).
city(eindhoven, 161.871/382.839).
city(groningen, 233.871/582.030).
city(haarlem, 103.690/488.416).
city(hertogenbosch, 149.225/412.119).
city(leeuwarden, 182.605/583.855).
city(maastricht, 176.830/318.793).
city(rotterdam, 92.548/437.734).
city(utrecht, 135.923/456.419).
city(zwolle, 203.252/503.130).

I implemented a program for this cause, but it doesn't seem to work:

estimate(State/NextState, Estimate) :-
    city(State, X/Y),
    city(NextState, X1/Y1),
    X2 is X1 - X,
    Y2 is Y1 - Y,
    Estimate is X2^2 + Y2^2,
    DifferentVar is sqrt(Estimate),
    estimate(State/NextState, DifferentVar).

If a query something like this it returns false:

?- estimate(amsterdam/utrecht, X).
false.

?- estimate(utrecht/amsterdam, X).
false.

I also tried this, but it doesn't work:

estimate(State/NextState, Estimate) :-
    city(State, X/Y),
    city(NextState, X1/Y1),
    Estimate is sqrt((X1 - X)^2 + sqrt(Y1 - Y)^2).

I have checked each 'subgoal' and I can't find the mistake or the wrong implementation. In my eyes it seems to me that each 'subgoal' has been reached, but it still returns false. I would really appreciate it if somebody could help me further!


Solution

  • The estimation rule should be:

    estimate(State/NextState, Estimate) :-
        city(State, X/Y),
        city(NextState, X1/Y1),
        X2 is X1 - X,
        Y2 is Y1 - Y,
        Estimate is sqrt(X2^2 + Y2^2).
    

    Note that only the last line changed (and the next 2 lines were deleted).