I’m trying to solve a problem where i have a list of coordinates and want to get the closest to a point.
Example:
I got the coordinates [[1,2],[3,4],[10,3]] and want to get the closest point to the origin [0,0]. [1,2] in this example.
I wrote this:
list_min([H|T], Min):-
list_min(T, H, Min).
list_min([], H, H).
list_min([L|Ls], Min0, Min) :-
point(P),
distance(Min0,P,D0),
distance(L,P,D1),
Lower is min(D0, D1),
assert(candidate(Min0)),
assert(candidate(L)),
forall(candidate(X),distance(X,P,Lower)),
retractall(candidate(_)),
list_min(Ls, X, Min).
distance(A,B,D):-
A = [A1,A2],
B = [B1,B2],
Y is B2 - A2,
X is B1 - A1,
D is sqrt(X*X + Y*Y).
However, looks like it always fail in forall line. What i’m doing wrong? Is there a better way for doing this?
I propose a solution without the suggested library or the quadtree, I stay in basic prolog (I write in SWI).
There is actually no need for
assert/retract/forallif I understand your problem correctly. I assume thatpoint(P)says that P is the uniquely-defined reference point from which we calculate distances, but it is a bit weird (I would use it as a parameter, to ensure it is unique).