Prolog sum of acalculation -


i have cartesian coordinates definition:

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

and "route" definition:

route(path1, [a, c, b, d]). 

then have function calculate distance between 2 points, this:

distance(p1, p2, d):-point(p1, x1, y1), point(p2, x2, y2),  z ((x2-x1)*(x2-x1))+((y1-y2)*(y1-y2)),  z >= 0,  d sqrt(z). 

how can calculate full distance of route?

also, if have several routes how can find longest one?

edit: should correct now

first, find length of given route, using distance function have provided:

path_len(path, d) :- route(path, [first|points]), path_len(points, first, 0, d).  path_len([], _last, dist, dist). path_len([p|points], prev, dacc, dist) :-     distance(prev, p, d),     ndacc dacc+d,     path_len(points, p, ndacc, dist). 

where dacc accumulator distance far (initialized 0). can query with

?- path_len(path1, d). 

if have several routes defined (do understand correctly?), path_len/2 calculate total distance of of them backtracking. can build distance-path pairs , use keysort/2 sort them , maybe reverse/2 put last 1 first:

longest_path(path, dist) :-     bagof(d-p, path_len(p, d), dppairs),     keysort(dppairs, sorted),     reverse(sorted, [dist-path|_]). 

you have used last/2 instead of reverse/2 on last line of predicate definition:

last(sorted, dist-path). 

Comments