I am trying to implement code in Prolog that will split a list into two parts. Basically, if it is of even length the result is trivial, since the halves are the same size. But for the odd case the left part must contain one more element than the one on the right. It is explained with the following example:
?- div([1,2,3,4,5],X,Y). %Largo impar
X = [1,2,3]
Y = [4,5]
The implementation I thought of, watching some videos and tutorials, was the following:
div(L, A, B) :-
append(A, B, L),
length(A, N),
length(B, N).
div(L, A, B) :-
append(A, B, L),
length(A, N),
N1 is N + 1,
length(B, N1).
However, for cases where the list is of odd length, it returns:
?- div([1,2,3,4,5],X,Y).
X = [1,2]
Y = [3,4,5]
I don't know what I may be missing to organize the elements well in the odd length lists. I hope someone can guide me.