简体   繁体   English

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

[英]How to arrange a list in ascending order in prolog?

i want to sort my list in ascending order but without using builtin function is that possible?我想按升序对列表进行排序,但不使用内置 function 这可能吗?

 5  9   3   4   7   10  2   1   5   6

if yes then how?如果是,那怎么办?

You can implement the sort yourself, writing predicates.您可以自己实现排序,编写谓词。 Let's implement selection sort (worst sort, but easy to understand and implement).让我们实现选择排序(最差排序,但易于理解和实现)。

The first thing to implement is a predicate that, given a list, find both the minimum and the list without the minimum:首先要实现的是一个谓词,给定一个列表,找到最小值和没有最小值的列表:

% 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].

Once you have this predicate, it's easy to write the sort predicate:一旦有了这个谓词,就很容易编写排序谓词:

% 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].

Of course, this algorithm is really bad, you definitely would prefer to implement a better sorting algorithm, such as merge sort.当然,这个算法真的很糟糕,你肯定更喜欢实现更好的排序算法,比如归并排序。 The goal here is just to show how this can be done with Prolog.这里的目标只是展示如何使用 Prolog 完成此操作。

We can just express our wishes, and Prolog will take it as its command:我们只要表达我们的意愿,Prolog就会把它作为它的命令:

ascending(  [], [] ).
ascending(  [A], [A] ).
ascending(   A,  [X,Y|C] ) :-
  select( X, A, B),
  ascending(    B, [Y|C] ),
          X   <     Y.

This runs very slowly though:不过,这运行得很慢:

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