I am a new Prolog developer and am trying to get merge sort working.The query
mergesort([2,1],T).
Will Produce
T=[1,2];
T=[1,2];
T=[1,2];
...
So Although it seems to "correctly" sort the sequence it doesn't halt
On the other hand if I had a query such as
mergesort([2,1],[2,1])
It gets into an infinite loop. I am wondering why this is the case?
append([H|T],LISTB,[H|LISTC]):-
append(T,LISTB,LISTC).
split(LIST,L1,L2):-
length(LIST,LENGTH),
M is div(LENGTH,2),
append(L1,L2,LIST),
length(L1,L1LENGTH),
(L1LENGTH =:= M).
merge(A,[],A).
merge([],B,B).
merge([A|TA],[B|TB],[A|MERGED]) :-
A =< B,
merge(TA,[B|TB],MERGED).
merge([A|TA],[B|TB],[B|MERGED]) :-
B < A,
merge([A|TA],TB,MERGED).
mergesort([],[]).
mergesort([X],[X]).
mergesort(LIST,OLIST):-
split(LIST,L1,L2),
mergesort(L1,OLIST1),
mergesort(L2,OLIST2),
merge(OLIST1,OLIST2,OLIST).