Prolog:列表中的排序子列表

时间:2014-11-05 18:10:27

标签: list prolog sublist

如何制作? 我需要这样的东西:

?- 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.

感谢您的帮助。

2 个答案:

答案 0 :(得分: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 .

答案 1 :(得分: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]].