I am writing a predicate in Prolog to divide a list into two equal in length lists. For example :
div([1,2,3,4] , X , Y).
X = [1,2].
Y = [3,4].
That's my code but it's not working :
div(L , L1 , L):- length(L) == length(L1).
div([ H | T ] , [ H | T1] , L2):- div(T , T1 , L2).
is not how you compare lengths of lists in Prolog. It compares the ''terms''
length(L)
andlength(L1)
without interpreting them, i.e. without calling any predicates. To compare lengths, doIf you fix that, your program should be closer to working.
Could be just:
Read as "appending list A and list B results in original list L, length of A is some value N and also length of B is the same value N".
It would just be,
It's just this, works with odd lenght :)
Funny is this split which doesn't use length :
For a list of 100 000 elements, it uses 50 001 inferences but 0,016 CPU, for the same list, lurker's code uses 50 015 inferences and 0,000 CPU.
I like Sergey's solution for its elegance and simplicity (+1). Here's another approach which is less elegant in favor of some further efficiency as it prunes the cases where
append
is queried. If eitherA
orB
are ground, then we let their length drive the process. Otherwise, we let the length ofL
drive it:And this will yield, for example:
Etc.