Hi everyone this is my first post so if you have any suggestions on how to ask questions I'm all ears. so on to my question I'm trying to sort a list of numbers using recursion, I have a my_max/2 predicate that returns the max of a list so after that returns I select that value from the list and then add it to my sorted list. then I recurse with the new list.
My problem is that the predicate seems to work and find the correct list but when the predicate exits it puts all the lists back to their original state basically undoing all of the work the predicate did. I think it has something to do with how Prolog backtracks?
%finds the max of a list, if the list is empty return int_min
my_max([],-2147483647).
my_max(L,M):-select(M,L,Rest), \+ (member(E,Rest),E>M).
%calls the my_max predicate store it in X, combines x and sorted and appends
%it to sorted2,then it takes X out of unsorted and creates Unsorted2 then
%recurse with unsorted2 and sorted2 should stop and output when unsorted is
%empty or []
my_sort([],S).
%my_sort([],S):-write(S). for test
my_sort(Unsorted,Sorted):-
my_max(Unsorted,X),
append(Sorted,[X],Sorted2),
select(X,Unsorted,Unsorted2),
my_sort(Unsorted2,Sorted2).
I added the the write just to show that it sorted the list. the output should be S=[3,2,1,1].
my_sort([], S).state that sorting an empty list gives an arbitrary resultS? - melpomene