slowsort(X,Y) :-  perm(X,Y), sorted(Y).

sorted([]).
sorted([X]).
sorted([X,Y|Z]) :- less_eq(X,Y), sorted([Y|Z]).

perm([],[]).
perm([X|Y],[U|V]):- delete(U,[X|Y],Z), perm(Z,V).

delete(X,[X|Y],Y).
delete(X,[Y|Z],[Y|Z1]):- delete(X,Z,Z1).

less_eq(0,X).
less_eq(s(X),s(Y)):- less_eq(X,Y).

%para testar executar: teste(X).
teste(X):- slowsort([s(s(0)),s(0),s(s(s(0)))],X).
 

nesimo(s(0),[X],X).
nesimo(s(X),[Y|Z],N):-nesimo(X,Z,N).

nesimol(1,[X|_],X).
nesimol(N,[_|L],X):- N>1, N1 is N-1,  nesimol(N1,L,X).

max(X,Y,X):-less_eq(Y,X).
max(X,Y,Y):-less_eq(X,Y).
