Prolog 计数排序

Prolog counting sort

所以我使用 ECLiPSe 6.1 在 Prolog 中创建了计数排序 (https://en.wikipedia.org/wiki/Counting_sort) 程序。它排序很好,但它只能在控制台中写入排序列表,而不是 return 将其作为第二个变量。那么如何使 return 排序列表成为变量呢?
例如:

mysort([1,1,6,7,4,1.5,11,6,7],Z) 

正在控制台中写入 ([7, 7, 6, 6, 4, 1, 1]) ,这是正确答案(它将数字从 0 排序到 10)。但是变量 Z 是 Z=Z,而不是Z=([7, 7, 6, 6, 4, 1, 1])

      build(_,0,[]).  %create list with ARG1 value , ARG2 size, and write to ARG3
      build(X,N1,[X|L]) :- N1 > 0, N is N1 - 1, build(X,N,L). 
      build(X,N1,[X]):- N1>0, N1 is N - 1, build(X,N,[]).  

      build_list(X,N):-build(0,N,X).%create list with ARG1 value , ARG2 size, and write to ARG3

      sum_list([], 0).% ARG1 list sum, write to ARG2
      sum_list([H|T], Sum) :-
         sum_list(T, Rest),
         Sum is H + Rest.

      replace([_|T], 0, X, [X|T]).%replace in ARG1 list,  ARG2 index with           ARG3 value,return as ARG4
      replace([H|T], I, X, [H|R]):- I > -1, NI is I-1, replace(T, NI, X, R), !.
      replace(L, _, _, L).

      increment_nth_in_list( [] , [],_ ) .%Increment element in ARG1, return as ARG2, increment element on ARG3 position
      increment_nth_in_list( [X|Xs] , [Y|Ys],N) :-
        (N=0->Y is X+1,N1 is N-1;
        N1 is N-1,Y is X),
        increment_nth_in_list(Xs,Ys,N1).    

      decrement_nth_in_list( [] , [],_ ) .%Decrement element in ARG1, return as ARG2, Decrement element on ARG3 position
      decrement_nth_in_list( [X|Xs] , [Y|Ys],N) :- 
        (N=0->Y is X-1,N1 is N-1;
         N1 is N-1,Y is X),
        decrement_nth_in_list(Xs,Ys,N1).    

      mysort([],[]).
      mysort([_],[]).
      mysort(Sorting,Sorted):-%Starting sort
      build_list(Amounts_of,10),%create list from 0 to 10 (MAX)
      count_numbers(Sorting,Amounts_of).%starting to count numbers

      count_numbers([Sortinghead|Sortingtail],Amount_of):-%counting numbers from ARG1 and writing to ARG2
      increment_nth_in_list(Amount_of,NewAmount,Sortinghead),
      length(Sortingtail,Z),
      (Z>0->count_numbers(Sortingtail,NewAmount);
      sum_list(NewAmount,Sum),build_list(Sorted,Sum),length(Sorted,L),fill_list(NewAmount,Sorted,0,L)
      ).

      fill_list([],A,_,_):-write(A).
      fill_list([Amount_of_Head|[]],[Sorted],N,L).

      fill_list([Amount_of_Head|Amount_of_Tail],Sorted,N,L):-%Filling ARG2           based on values in ARG1,with ARG3 values on ARG4 position.
      Amount_of_Head>0-          >decrement_nth_in_list([Amount_of_Head|Amount_of_Tail],NewAmount,0),L1 is L-          1,replace(Sorted,L1,N,NewSorted),fill_list(NewAmount,NewSorted,N,L1)
      ;N1 is N+1,fill_list(Amount_of_Tail,Sorted,N1,L).

您的调用中的第二个参数 Z 对应于 mysort/2 最后一个子句中的变量 Sorted。但是该子句从不使用该变量,因此它永远不能绑定到解决方案。完成后,您必须将参数添加到绑定到解决方案的 fill_list/4count_numbers/2,在您现在执行 write 的同一点。 (您可能能够重用现有参数;您的代码格式错误并且您的变量名无助于理解它。)