Another day, another question!
The book I’m reading gave an exercise to write a predicate dividelist(L1, L2, L3) so that L2 and L3 are the contents of L1 divided, eg dividelist([1,2,3,4,5], [1,3,5], [2,4]). would be true.
My attempt at this wasn’t very elegant, and didn’t work (see below). The author gave a very neat piece of code that does work, which I understand, but I’m interested to know where I went wrong.
My initial thought was to use an auxiliary predicate that has a fourth parameter that indicates if we are to add the head of the first list to the second or third list. I would then have two versions of the auxiliary predicate, one for when the fourth parameter were true and one for when it were false. This led to the following (rather convoluted) code…
dividelist(List, Part1, Part2) :-
dividelist_(List, Part1, Part2, true).
dividelist_([], _, _, _).
dividelist_([H|T], Part1, Part2, true) :-
dividelist_(T, [H|Part1], Part2, false).
dividelist_([H|T], Part1, Part2, false) :-
dividelist_(T, Part1, [H|Part2], true).
However, this always returns true, even if the parameters don’t match. So the following all return true…
dividelist([1,2], L1, L2).
dividelist([1,2,3,4], L1, L2).
dividelist([1,2], [], []).
dividelist([1,2,3,4], [1,2], [3,4]).
% etc...
More to the point, I never get the variables bound, I just get true returned.
Anyone able to explain why this code doesn’t bind the variables?