Search code examples
prologprolog-dif

Prolog separating into two lists issue


I have a prolog assignment.

I need to look at the first item in a list, see if its following items are the same until they are not and separate the lists by the first item and its duplicates. e.g if my list was a,a,a,b,c it would separate it into first: a,a,a. second: b,c.

My current solution works except that the final matching item comes into the second list, not the first. I can't seem to think of a way to get it to appear in the first list instead.

grab([],[],[]).
grab([A,A|L],[A|L2],Rest) :- grab([A|L],L2,Rest).
grab([A|L],Init,[A|L2]) :- grab(L,Init,L2).

Solution

  • When the first two elements are different you do not need a recursive goal.

    grab([], [], []).
    grab([A,A|Rest], [A|As], L2):- !, grab([A|Rest], As, L2).
    grab([A|Tail], [A], Tail).