Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter list into separate lists

I need to filter the list [#,d,e,#,f,g] such that I get the output as [[d,e],[f,g]] ,
I am stuck while creating a new list every time I encounter '#' 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)
   ).
like image 899
sand Avatar asked Jun 26 '26 18:06

sand


1 Answers

Here is another version, which uses 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 of

   all_seq(callfalse(C_2),Xs)

and the definition for callfalse/3, one can now write

   all_seq(C_2+\F^call(C_2,F,false))
like image 106
false Avatar answered Jun 30 '26 17:06

false



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!