1

I have a list C and I want to split the list using the element c in the list.

The expected results are as example:

?- split([a,c,a,a,c,a,a,a],X).
X = [[a],[a,a],[a,a,a]].

Can anybody help? Thanks in advance.

I can remove the c in the list now and here is my codes.

split([],[]).
split([H|T],[H|S]) :- H=a,split(T,S).
split([H|T],S) :- H=c,split(T,S). 
repeat
  • 18,496
  • 4
  • 54
  • 166

3 Answers3

1

Your "remove c" predicate would look better like this:

remove_c([c|T], S) :-
    remove_c(T, S).
remove_c([a|T], [a|S]) :-
    remove_c(T, S).

This still only works for lists that have only c and a in them.

If you want to "split", this means you at least need another argument, to collect the a's between the c's. For example:

split_on_c(List, Split) :-
    split_on_c_1(List, Split, []).

split_on_c_1([], [Acc], Acc).
split_on_c_1([c|Rest], [Acc|Split], Acc) :-
    split_on_c_1(Rest, Split, []).
split_on_c_1([a|Rest], Split, Acc) :-
    split_on_c_1(Rest, Split, [a|Acc]).

Again, this expects lists of a and c only. It could also be done in different ways, but this is a start.

1

While learning a language you need to get accomplished to common abstractions already established (in simpler terms, use libraries). What about

split(In, Sep, [Left|Rest]) :-
    append(Left, [Sep|Right], In), !, split(Right, Sep, Rest).
split(In, _Sep, [In]).

to be used like

?- split([a,c,a,a,c,a,a,a],c,R).
R = [[a], [a, a], [a, a, a]].
CapelliC
  • 59,646
  • 5
  • 47
  • 90
1

Use the splitlistIf/3 together with reified term equality (=)/3, like this:

Here is the query the OP gave in the question:

?- splitlistIf(=(c),[a,c,a,a,c,a,a,a],Xs).
Xs = [[a],[a,a],[a,a,a]].

Note that above code is monotone, so the following query gives reasonable results:

?- splitlistIf(=(X),[Y,X,Y,Y,X,Y,Y,Y],Xs), Y = a, X = c.
X  = c,
Y  = a,
Xs = [[a],[a, a],[a, a, a]].
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166