0

I want to write a predicate split(List, Pivot, Result) holds when Result is a list of sublists that List divided by Pivot. For example split([A, B, '#', C, '#', D], '#', [[A, B], [C], [D]]) is true. Note that the elements are lists with logic variables.

I asked a question about how to do this to lists which do not have logic variables as elements. Here's the answer:

split(L,P,R):-split(L,P,[],R).
split([],_,[],[]).
split([],_,S,[S]) :- S \= [].
split([P|T],P,[],R) :- split(T,P,[],R).
split([P|T],P,L,[L|R]) :- L \= [], split(T,P,[],R).
split([H|T],P,S,R) :- H \= P, append(S, [H], S2), split(T,P,S2,R).

However this does not work with the lists which have logic variables as elements. Any suggestions to solve this problem? Thank you!

user3928256
  • 903
  • 1
  • 11
  • 17
  • 2
    possible duplicate of [filter list into separate lists](http://stackoverflow.com/questions/26439058/filter-list-into-separate-lists) – false Oct 23 '14 at 22:47
  • I can't understand the answer of that question. There are a lot of features that I've never seen before. I tried the solution but couldn't understand what I saw. – user3928256 Oct 23 '14 at 23:10
  • your problem looks like `join`, have you thought about that? – Patrick J. S. Oct 24 '14 at 01:35

1 Answers1

1

You were very nearly there.

Consider this slightly modified version:

split(L, P, R) :- split(L, P, [], R).
split([], _P, [], []) :- !.
split([], _P, Acc, [Acc]).
split([X|Xs], P, Acc, Result) :-
    X \== P, !,
    append(Acc, [X], NewAcc),
    split(Xs, P, NewAcc, Result).
split([_X|Xs], P, [], Result) :- !, split(Xs, P, [], Result).
split([_X|Xs], P, Acc, [Acc|Result]) :- split(Xs, P, [], Result).

This implementation relies on the accumulator as you'd tried, but simply shunts the accumulator into the result list as soon as the list item doesn't match the pivot using \==/2.

  • Umm.. This generate `[]`, for example `?- split(['#', A,'#',B,ASD,D,'#'], '#', X). X = [[], [A], [B, ASD, D], []] .` It should be `[[A], [B, ASD, D]]`. Can you fix it? – user3928256 Oct 24 '14 at 03:10