[英]How to arrange a list in ascending order in prolog?
我想按升序對列表進行排序,但不使用內置 function 這可能嗎?
5 9 3 4 7 10 2 1 5 6
如果是,那怎么辦?
您可以自己實現排序,編寫謂詞。 讓我們實現選擇排序(最差排序,但易於理解和實現)。
首先要實現的是一個謂詞,給定一個列表,找到最小值和沒有最小值的列表:
% Case where the list has only one element, pretty easy.
mini([H], H, []).
% H is the head of the list, T is the tail, M is the minimum of the list and R
% is the remaining list/elements (without the minimum).
% In the following predicate, H is NOT the minimum of the list.
mini([H|T], M, R) :- mini(T, M2, R2), M2 =< H, M = M2, R = [H | R2].
% Same as above, but when H (head) is the minimum of the list.
mini([H|T], M, R) :- mini(T, M2, R2), M2 > H, M = H, R = [M2 | R2].
一旦有了這個謂詞,就很容易編寫排序謂詞:
% Easy case where the given list is empty
mysort([], []).
% L is the list to sort, R is the resulted sorted list.
% This predicate will first retrieve the minimum and the list without
% the minimum, sort again the rest of the list and concatenate the
% sorted remaining list with the minimum element found.
mysort(L, R) :- mini(L, M, Rem), mysort(Rem, T2), R = [M|T2].
當然,這個算法真的很糟糕,你肯定更喜歡實現更好的排序算法,比如歸並排序。 這里的目標只是展示如何使用 Prolog 完成此操作。
我們只要表達我們的意願,Prolog就會把它作為它的命令:
ascending( [], [] ).
ascending( [A], [A] ).
ascending( A, [X,Y|C] ) :-
select( X, A, B),
ascending( B, [Y|C] ),
X < Y.
不過,這運行得很慢:
2 ?- ascending( [5,9,3,4,7,10,2,1,5,6], X).
false.
% Execution Aborted
3 ?- ascending( [5,9,3,4,7,10,2,1,6], X).
X = [1, 2, 3, 4, 5, 6, 7, 9, 10] ;
false.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.