排序谓词

时间:2015-01-20 14:54:42

标签: prolog

我有这个谓词,

date(YYYY,MM,DD).
immigrant(IdPerson,Date).

我想知道最近移民的IdPerson。我看到了解决方案,我得到了这个:

most_recent_immigrant(IDPerson):-
    findall(immigrants1(Data,IdPerson), immigrant(IDPerson,Data), ListOfImmigrants).
    sort(ListOfImmigrants,List),
    last(List, immigrants1(Data,IDPerson)).

所以,如果我理解这个练习,我们需要按日期排序,但是如何单独排序呢?或者我还需要别的东西来完成这项工作吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

most_recent_immigrant( Immigrant ) :-
  findall( immigrant(X,D) , immigrant(X,D) , L ) ,
  predsort( immigrant_compare , L , [Immigrant|_] ) .

immigrant_compare( = , immigrant(_,X) , immigrant(_,X) ) :- X = Y .
immigrant_compare( < , immigrant(_,X) , immigrant(_,Y) ) :- X > Y .
immigrant_compare( > , immigrant(_,X) , immigrant(_,Y) ) :- X < Y .

但是,既然你可能在任何特定的日期有多个移民,我可能会这样做:

most_recent_immigrants( Immigrants ) :-                   % to find the most recently arrived immigrant(s)...
  setof( D , immigrant(_,D) , Ds ) ,                      % get the [ordered] set of dates
  last( M , Ds ) ,                                        % the last item is the most recent dates
  findall( immigrant(N,D) , immigrant(N,D) , Immigrants ) % find all the immigrants on the specified date
  .