I have just started with Prolog, by reading Brue Tates book "Seven Languages in Seven Weeks".
Two of the exerices in the Prolog chapter are:
* Find the smallest element in a list
* sort the elments in a list
My Idee was to solve the second problem by using the solution of the first one. (Of course just could use the sort/2 of SWI Prolog, but this not what an exercise is about.)
min([H|T],X) :- T=[], X=H.
min([H|T],H):- T\=[], min(T,Min_Tail), Min_Tail>H.
min([H|T],X):- T\=[], min(T,X), X=<H.
The Minimum should be the first element in the sorted List. Now I want to delete the minimum from the given list and proceed with this shorted list. There for, I created remove/3, which should be used to delete the first occurrence of a given item in the list.
remove(Item, [H|T], Result) :- Item=H, Result=T.
remove(Item, [H|T], Result) :- Item\=H, remove(Item, T, Y), Result=[H|Y].
sor(X, [H|T]) :- T=[], X=[H].
sor(X, [H|T]) :- T\=[], min(X,H), remove(H, X, Y), sor(Y,T).
sor can find out, weather a list is sorted correctly:
?- sor([3,2,1],[1,2,3]).
true .
?- sor([1,4,55,3,2,1],[1,1,2,3,4,55]).
true .
?- sor([3,2,4],[2,4,3]).
false.
but sort does not find a solution by it self: