Based on some facts, I have to find the oldest person using Prolog. For example:
age(john, 10).
age(mary, 15).
age(rose, 75).
age(jack, 49).
age(carl, 17).
age(lucy, 66).
Console output should be:
?- oldest(rose).
True.
?- oldest(X).
X = rose.
My code is as follows, but it's not working:
oldest(P) :- age(P, X) , age(_, Y) , X >= Y.
I can't find the error, but I guess it's something related to backtrack. Could someone help me, please? I'm new to Prolog.
the correct one should be
oldest(P) :- age(P, X) , \+ (age(_, Y) , Y > X).
that yields rose, of course...
(\+)/1
read as not(Goal), and means 'fail if there are no solutions to Goal'.
edit in SWI-Prolog, library(aggregate) can do this, and much more...
oldest(P) :- aggregate(max(A,Pers), age(Pers,A), max(_,P)).
Your oldest/1
definition is not valid (and CapelliC's answer shows why and how to fix it).
Here is another way find an oldest person:
oldest(X) :-
findall((Age, Name), age(Name, Age), List),
sort(List, SList),
reverse(SList, [(_, X) | _]).