. 먼저 소스 목록을 반복하여 발견 된 각 하위 목록을 정렬합니다. 완료되면 실제로 최종 목록을 정렬합니다. 그 이유는 반복되는 하위 목록 정렬을 피하기 위해서입니다. 이 같은
뭔가 :
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
각 데와 사물의 표준 순서로 두 용어를 비교하여 원자를 반환하는 기본 조건, <
중 하나 =
, >
는 것을 명백한 의미. 원하는 경우 자신의 롤 수 있습니다 :