简体   繁体   中英

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?

 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.

We can just express our wishes, and Prolog will take it as its command:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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