I am trying to make a function that splits a list of variable length into three lists of even length in order. The following splits it into three, but processes inserts them into each list one at a time.
An example of what I want is:
[1, 2, 3, 4, 5] -> [1, 2], [3, 4], [5]
Another example would be:
[8, 7, 6, 5, 4, 3, 2, 1] -> [8, 7, 6], [5, 4, 3], [2, 1].
The following code splits them by inserting into each list one at a time:
div([], [], [], []).
div([X], [X], [], []).
div([X,Y], [X], [Y], []).
div([X,Y,Z|End], [X|XEnd], [Y|YEnd], [Z|ZEnd]):-
div(End, XEnd, YEnd, ZEnd).
This code outputs:
[1, 2, 3, 4, 5] -> [1, 4], [2, 5], [3]
How can I fix this problem?
The answer by @Boris does not terminate when the length of the list of the first argument is not known. To see this, there is no need to look any further than the first goal with a failure-slice:
On the other hand, your original program had quite nice termination properties. cTI gave the following optimal termination property:
In other words, to ensure termination, you only need a single argument (either
A
orB
orC
orD
) to be a concrete list that is finite and ground (that's whatb(..)
means). That is a very strong termination condition. It's really a pity that the arguments do not fit! Why not generalize your program? The only problem it has it that it restricts the list elements. So I will replace all variable names of list elements by_
s:The very same termination properties hold for this program.
Alas, it is now a bit too general. Boris's solution can now be repurposed:
My preferred way to express the same would rather be:
See other answers for a definition of
seq//1
.Do you see how this splits the three lists? Now you don't say how long you expect the lists
L1
,L2
, andL3
to be. You can uselength/2
to get the length ofL
and set the length of the three results if you don't want the predicate to be as general as it is at the moment.Since you say "relatively even length", which is relative and I need to interpret it somehow, lets assume you mean that, for a positive integer len and n, len = 3n, you get len1 = len2 = len3 = n, for k = 3n+1 you get len1 = n+1, len2 = len3 = n, and for k = 3n+2 you get len1 = len2 = n+1, len3 = n. I let you figure out how to compute the lengths.