所以我使用ECLiPSe 6.1在Prolog中创建了计数排序(https://en.wikipedia.org/wiki/Counting_sort)程序。它排序很好,但它只能在控制台中编写排序列表,而不是将其作为第二个变量返回。那么如何让它将排序列表作为变量返回? 例如:
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).
答案 0 :(得分:1)
您的调用中的第二个参数Z
对应于Sorted
的最后一个子句中的变量mysort/2
。但该子句从不使用该变量,因此它永远不会绑定到解决方案。完成后,您必须添加绑定到解决方案的fill_list/4
和count_numbers/2
的参数,与现在执行write
的位置相同。 (您可能可以重用现有的参数;您的代码格式错误,并且您的变量名称无法理解它。)