我在Prolog中有这个列表:
[[13,Audi A3,11.11.2011,75000,berlina,audi,12100,verde pisello,[4wd],3.0000133333333334],[11,santafe,11.11.2011,80000,fuoristrada,audi,2232232,verde pisello,[Metalizzata,Sedile in Pelle,4wd],7.0000125]] |
我想将此列表排序为子列表的最后一个值,例如我希望得到这个结果:
[[11,santafe,11.11.2011,80000,fuoristrada,audi,2232232,verde pisello,[Metalizzata,Sedile in Pelle,4wd], 7.0000125 ],[13,Audi A3, 11.11.2011,75000,berlina,audi,12100,verde pisello,[4wd], 3.0000133333333334 ]]
答案 0 :(得分:1)
predsort这是你的朋友。然后排序很容易,但出售奥迪verde pisello
将会非常非常困难......
sort_on_last(List, Sorted) :-
predsort(compare_last, List, Sorted).
compare_last(R, X, Y) :-
last(X, Xl),
last(Y, Yl),
compare(R, Xl, Yl).
试一试:
test :- sort_on_last(
[[11,santafe,'11.11.2011',80000,fuoristrada,audi,2232232,'verde pisello',['Metalizzata','Sedile in Pelle','4wd'],7.0000125],
[13,'Audi A3','11.11.2011',75000,berlina,audi,12100,'verde pisello',['4wd'],3.0000133333333334]
], S),
maplist(writeln, S).
?- test.
[13,Audi A3,11.11.2011,75000,berlina,audi,12100,verde pisello,[4wd],3.0000133333333334]
[11,santafe,11.11.2011,80000,fuoristrada,audi,2232232,verde pisello,[Metalizzata,Sedile in Pelle,4wd],7.0000125]
true.
predsort / 3的特殊性:它充当sort / 2,因此删除重复。 为了避免这个问题,可以改变compare_last / 3,避免以这种方式返回 = :
compare_last(R, X, Y) :-
last(X, Xl),
last(Y, Yl),
( Xl < Yl -> R = (<) ; R = (>) ).