Selection sort in prolog

3.2k Views Asked by At

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?

2

There are 2 best solutions below

8
coder On BEST ANSWER

As well pointed out by @Boris the main mistake was in min/2 predicate 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:

ssort([],[]).
ssort([M1|S],[H|T]):-min(H,T,M1),remove(M1,[H|T],N),ssort(S,N).

min(M,[],M).
min(M,[H|T],M1):-min2(M,H,N),min(N,T,M1).

min2(A,B,A):-less(A,B).
min2(A,B,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).

Example:

?- ssort(S,[5,3,1]).
S = [1, 3, 5] ;
false.

?- ssort(S,[5,3,1,7]).
S = [1, 3, 5, 7] ;
false.

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.

0
false On

Here is a general way how you can at least localize the error in your program. If your query fails, simply remove goals from your program. If the remaining fragment still fails, there must be an error in that fragment.

:- op(950,fy,*).
*_.

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).

?- ssort(S,[5,3,1]).

Because this fragment fails, your original program will fail as well. You need to generalize something in the remaining part.