List 如何在prolog中按升序排列列表?
我想按升序对列表排序,但不使用内置函数,这可能吗List 如何在prolog中按升序排列列表?,list,sorting,prolog,List,Sorting,Prolog,我想按升序对列表排序,但不使用内置函数,这可能吗 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
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].
当然,这个算法非常糟糕,您肯定更愿意实现更好的排序算法,例如合并排序。这里的目标只是展示如何使用Prolog实现这一点。我们可以表达我们的愿望,Prolog将把它作为它的命令:
ascending( [], [] ).
ascending( [A], [A] ).
ascending( A, [X,Y|C] ) :-
select( X, A, B),
ascending( B, [Y|C] ),
X < Y.
是的,您实现了一个排序谓词。因为我不熟悉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.