I'm new in Prolog and I'm trying to make the selection sort. Here is what I have:
ssort([],[]).
ssort([M|S],L):-min(M,L),remove(M,L,N),ssort(S,N).
min(M,[M]).
min(M,[H,T]):-min(N,T),min2(M,H,N).
min2(A,A,B):-less(A,B).
min2(B,A,B):-not(less(A,B)).
less(A,B):-(A<B).
append([],B,B).
append([H|A],B,[H|AB]):-append(A,B,AB).
remove(X,L,N):-append(A,[X|B],L),append(A,B,N).
But when I try this for example:
ssort(S,[5,3,1]),write(S).
I get false, no matter what I try. Can you tell me how can I actually sort the list and get the result written in S?
As well pointed out by @Boris the main mistake was in
min/2predicate because it needs a 3rd parameter in order to return the min element in that parameter. With a few small changes the code looks like:Example:
EDIT:
As @Will Ness correctly pointed out the only mistake was the comma in
min(M,[H,T])so changing to min(M,[H|T]) it works fine!!!. I thought that min/2 predicate wasn't working very well so I changed it in the answer above but finally this was not necessary.