How about using clpfd and lambda?
:- use_module(library(clpfd)).
:- use_module(library(lambda)).
We define split/3
like this:
split(Xs,N,Yss) :-
length(Xs,L),
N #=< L,
[L0,L1] ins 1..sup,
L0 #= L / N,
L1 #= L - L0*(N-1),
% enumerate `N` *now* if domain is finite.
% ideally, length/2 does something like this (by itself).
( fd_size(N,Size),integer(Size) -> indomain(N) ; true ),
length(Yss,N),
append(Yss0,[Ys],Yss), % creates useless choicepoint
maplist(\Ls^length(Ls,L0),Yss0),
length(Ys,L1),
append(Yss,Xs). % note we use append/2 here, not append/3
First, the queries the OP gave:
?- split([1,2,3,4,5,6,7,8],2,Lists).
Lists = [[1,2,3,4], [5,6,7,8]]
; false.
?- split([1,2,3,4,5,6,7,8],4,Lists).
Lists = [[1,2], [3,4], [5,6], [7,8]]
; false.
Then, a more general example:
?- split([1,2,3,4,5,6,7,8],N,Lss).
N = 1, Lss = [[1,2,3,4,5,6,7,8]]
; N = 2, Lss = [[1,2,3,4], [5,6,7,8]]
; N = 3, Lss = [[1,2], [3,4], [5,6,7,8]]
; N = 4, Lss = [[1,2], [3,4], [5,6], [7,8]]
; N = 5, Lss = [[1], [2], [3], [4], [5,6,7,8]]
; N = 6, Lss = [[1], [2], [3], [4], [5], [6,7,8]]
; N = 7, Lss = [[1], [2], [3], [4], [5], [6], [7,8]]
; N = 8, Lss = [[1], [2], [3], [4], [5], [6], [7], [8]]
; false.
split(L, N, S) :- length(S, N), append(S, L).
– CapelliC