Search exhaustively through a knowledge base in Prolog through a query

Viewed 29

If I have a knowledge base of people and their birthdays like:

birthYear( adam , 2000 ).
birthYear( bob  , 2001 ).
birthYear( john , 2002 ).

How would I create a query to exhaustively search the knowledge base to find the youngest person without modifying the knowledge base?

2 Answers

Can use aggregate_all:

person_year(adam, 2000).
person_year(bob, 2001).
person_year(john, 2002).

youngest_person(Person) :-
    % Find lowest year
    aggregate_all(min(Y), person_year(_P, Y), Year),
    % Lookup person from lowest year
    person_year(Person, Year).

Result in swi-prolog:

?- youngest_person(Person).
Person = adam.

Something like this?

youngest(P) :-
  findall( P:Y , birth_year(P,Y) , PYs ),
  most_recent_year( PYs, Y ),
  member(P:Y,Ps)
  .

most_recent_year( [_:Y|PYs], R ) :- most_recent_year(PYs,Y,R) .

most_recent_year( []        , R , R ) .
most_recent_year( [_:Y|PYs] , T , R ) :- Y > T , ! , most_recent_year(PYs,Y,R).
most_recent_year( [_|PYs]   , T , R ) :-             most_recent_year(PYs,T,R).
Related