Finding the oldest person in Prolog

2019-05-29 00:35发布

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.

标签: prolog
2条回答
beautiful°
2楼-- · 2019-05-29 01:13

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)).
查看更多
等我变得足够好
3楼-- · 2019-05-29 01:21

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) | _]).
查看更多
登录 后发表回答