Programming in Prolog: Sort List

Illustrated here is a program written in the logical language of Prolog.

This particular program defines a series of rules that will sort a list. It illustrates how a logical language can be used for more conventional algorithms like list sorting. Lets take a closer look at the code.


permute([], []).
permute(L, [H|T]) :- remove(H, L, R), permute(R,T).
remove(X, [X|T], T).
remove(X, [H|T], [H|NT]) :- remove(X,T,NT).

sorted([]).
sorted([_]).
sorted([X,Y|T]) :- X =< Y, sorted([Y|T]).

sortlist(List, Sorted) :- permute(List, Sorted), sorted(Sorted).

Here is an example input and output:

1 ?- sortlist([1,5,4],X).
X = [1, 4, 5] .

The output demonstrates that the provided list is sorted according to ascending order.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>