Filter list into separate lists

I need to filter the list [#,d,e,#,f,g]

to get the result like [[d,e],[f,g]]

,
I get stuck creating a new list every time I come across a "#", is there a way to do this? I tried the code below,

filterL([],List) :-[].
filterL([Head|Tail],X) :-
   (  Head \='#'->
      append(X,Head,List),
      filterL(Tail,List)
   ;  filterL(Tail,X)
   ).

      

+3


source to share


3 answers


Your problem is not well defined. Are empty sequences allowed or not? Should be [#]

associated with [[],[]]

(there is an empty sequence before and after) or []

? You say it should be []

. So:



list_splitbyhash(Xs, Xss) :-
   phrase(splitby(Xss,#), Xs).

splitby([],_E) -->
    [].
splitby(Xss,E) -->
    [E],
    splitby(Xss,E).
splitby([Xs|Xss],E) -->
    {Xs = [_|_]},
    all_seq(dif(E),Xs),
    splitby(Xss,E).

all_seq(_, []) --> [].
all_seq(C_1, [C|Cs]) -->
   [C],
   {call(C_1,C)},
   all_seq(C_1, Cs).

      

+4


source


Here's another version that takes an even more general approach:

list_splitbyhash(Xs, Xss) :-
   phrase(by_split(=(#), Xss), Xs).

=(X,X,true).
=(X,Y,false) :- dif(X,Y).

by_split(_C_2, []) --> [].
by_split(C_2, Xss) -->
   [E],
   {call(C_2,E,T)},
   (  { T = true },
      by_split(C_2, Xss)
   |  { T = false, Xss = [[E|Xs]|Xss1] },
      all_seq(callfalse(C_2),Xs),
      el_or_nothing(C_2),
      by_split(C_2, Xss1)
   ).

callfalse(C_2,E) :-
   call(C_2,E,false).

el_or_nothing(_) -->
   call(nil).
el_or_nothing(C_2), [E] -->
   [E],
   {call(C_2,E,true)}.

nil([], []).

      

With lambdas, this can be expressed more compactly. Instead



   all_seq(callfalse(C_2),Xs)

      

and definitions for callfalse/3

, now you can write

   all_seq(C_2+\F^call(C_2,F,false))

      

+3


source


With the meta predicate splitlistIf/3

and the reified equality predicate, the (=)/3

task at hand becomes one-line, which is efficient and logically clean !

?- splitlistIf(=(#),[#,d,e,#,f,g],Xs).
Xs = [[d,e],[f,g]].                      % succeeds deterministically

      

Because the code is monotonous , logical robustness is provided even for fairly general queries:

?- Xs = [A,B,C], splitlistIf(=(X),Xs,Yss).
Xs = [A,B,C],     X=A ,     X=B ,     X=C , Yss = [       ] ;
Xs = [A,B,C],     X=A ,     X=B , dif(X,C), Yss = [    [C]] ;
Xs = [A,B,C],     X=A , dif(X,B),     X=C , Yss = [  [B]  ] ;
Xs = [A,B,C],     X=A , dif(X,B), dif(X,C), Yss = [  [B,C]] ;
Xs = [A,B,C], dif(X,A),     X=B ,     X=C , Yss = [[A]    ] ;
Xs = [A,B,C], dif(X,A),     X=B , dif(X,C), Yss = [[A],[C]] ;
Xs = [A,B,C], dif(X,A), dif(X,B),     X=C , Yss = [[A,B]  ] ;
Xs = [A,B,C], dif(X,A), dif(X,B), dif(X,C), Yss = [[A,B,C]].

      

+2


source







All Articles