2014-11-05 86 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). 

样品输入:

?- 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是一个内置的谓词两个术语在事物的标准顺序进行比较,并返回一个原子,的<一个,=>,每个具有意义明显。如果您愿意,您可以推出自己的产品:

compare(<,X,Y) :- X @< Y . 
compare(>,X,Y) :- X @> Y . 
compare(=,X,Y) :- X == Y .