繁体   English   中英

如何在 prolog 中按升序排列列表?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM