2014-11-05 4 views
2

만드는 방법? 나는 이런 식으로 뭔가가 필요합니다프롤로그 : 목록의 하위 목록 정렬

?- elsort([d,s,a,[r,t,h]],X). 
X = [a, d, s, [h, r, t]]. 

을하지만 난이 얻을 :

?- elsort([d,s,a,[r,t,h]],X). 
X = [a, d, s, [r, t, h]]. 

내 코드 : 돕는

elsort([],[]). 
elsort([A|B],C):- 
    elsort(B,D), 
    elsortx(A,D,C). 

elsortx(A,[X|B],[X|C]):- 
    order(X,A), 
    !, 
    elsortx(A,B,C). 
elsortx(A,B,[A|B]). 

order(A,A2):- 
    A @< A2. 

감사합니다.

답변

1

는, 예를 들어 목록 경우 당신은 요소 자체를 정렬 할 필요가있을 것이다 :

elsort([A|B],C):- 
    elsort(B,D), 
    (is_list(A)->elsort(A, SA);SA=A), 
    elsortx(SA,D,C). 

샘플 입력 : 아마 하위 목록 2 단계 작업의 정렬을 만들 것

?- elsort([d,s,a,[r,t,h]],X). 
X = [a, d, s, [h, r, t]]. 
2

. 먼저 소스 목록을 반복하여 발견 된 각 하위 목록을 정렬합니다. 완료되면 실제로 최종 목록을 정렬합니다. 그 이유는 반복되는 하위 목록 정렬을 피하기 위해서입니다. 이 같은

뭔가 :

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 각 데와 사물의 표준 순서로 두 용어를 비교하여 원자를 반환하는 기본 조건, < 중 하나 =, >는 것을 명백한 의미. 원하는 경우 자신의 롤 수 있습니다 :