我很可能会令子列表两阶段操作的排序。首先,遍历源列表,对找到的每个子列表进行排序。完成后,然后实际排序最终列表。理由是避免重复排列子列表。
像这样:
my_sort(Unsorted , Sorted) :- % to sort a list of lists...
sort_sublists(Unsorted, U) , % - 1st pass: sort any sublists
merge_sort(U , Sorted) % - 2nd pass: actually sort the results
. %
sort_sublists([] , []) . % an empty list has no sublists to sort
sort_sublists([X|Xs] , [Y|Ys]) :- % otherwise...
list(X) , % - if the head is a list
!, % - eliminate the choice point
my_sort(X,Y) % - and sort the head (along with its sublists)
. %
sort_sublists([X|Xs] , [X|Ys]). % otherwise (the head is not a list)
merge_sort([] , []) . % an empty list is sorted.
merge_sort([A] , [A]) . % list of 1 item is sorted.
merge_sort([A,B|Cs] , Sorted) :- % otherwise, to sort a list of 2 or more items...
partition([A,B|Cs] , L , R) , % - partition it into two halves.
merge_sort(L , L1) , % - then recursively sort the left half
merge_sort(R , R1) , % - and recursively sort the right half
merge(L1 , R1 , Sorted) % - then merge the two now-order halves together
. % producing the final, sorted list
partition([] , [] , [] ) .
partition([L] , [L] , [] ) .
partition([L,R|Xs] , [L|Ls] , [R|Rs]) :- partition(Xs,Ls,Rs) .
merge([] , [] , [] ) .
merge([L] , [] , [L]) .
merge([] , [R] , [R]) .
merge([L|Ls] , [R|Rs] , [R,L|Xs]) :-
compare(CC,L,R) ,
swap(CC,L,R,Lo,Hi),
merge(Ls,Rs,Xs)
.
swap(< , L , R , L , R) .
swap(> , L , R , R , L) .
swap(= , L , R , L , R) .
list(X ) :- var(X) , ! , fail .
list([] ) .
list([_|_]) .
注意compare/3
是一个内置的谓词两个术语在事物的标准顺序进行比较,并返回一个原子,的<
一个,=
,>
,每个具有意义明显。如果您愿意,您可以推出自己的产品:
compare(<,X,Y) :- X @< Y .
compare(>,X,Y) :- X @> Y .
compare(=,X,Y) :- X == Y .