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:
but sort does not find a solution by it self: