Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Finding a maximum of all predicate parameters

Status
Not open for further replies.

Troman2

Programmer
Jun 12, 2008
2
0
0
DE
Hi, I'm new to prolog. I have folowing predicated in my program:

points(bob, 3).
points(ted, 10).
points(tom, 7).
points(ben, 5).


How do I find out who has the most points?

I don't know how to make Prolog iterate through all points() predicates and remember the highest value. Iterating through a list would be easier, but I'd like to stay away from lists if possible.

My first attempt was:

more_points(X,Y):- points(X, P1), points(Y, P2), P1 > P2.
less_points(X,Y):- points(X, P1), points(Y, P2), P1 < P2.
same_points(X,Y):- points(X, P1), points(Y, P2), P1 == P2, X \= Y.

most_points(X):- less_points(_, X),\+ more_points(_, X), \+ same_points(X, Y), !.


But I think it isn't the best way to do it and I cant come up with a better one. Does anyone know a better way?
 
I have rewritten the last part, it does seem to work now:

most_points(Most):- most_points(_, Most),!. %hides most_points\2, cuts duplicates
most_points(Old, New):- more_points(Current, Old), most_points(Current, New).
most_points(Old, New):- \+ more_points(_, Old), New = Old. %the line above fails when found someone with most points so this one will prevent failure


But I think there must be a more elegant solution to this. Does anyone know one?
 
I don't know if it is more elegant, but in SWI-Prolog you can do that :

:- dynamic(maximum/1).

points(bob, 3).
points(ted, 10).
points(tom, 7).
points(ben, 5).

number :-
points(_, N),
assert(maximum(N)),
forall(points(_,Val),
( retract(maximum(V1)),
( Val > V1 -> assert(maximum(Val)); assert(maximum(V1))))),
retract(maximum(M)),
write(M), nl.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top