filter list into separate lists

前端 未结 3 692
刺人心
刺人心 2020-12-21 08:53

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 encount

相关标签:
3条回答
  • 2020-12-21 09:07

    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))
    
    0 讨论(0)
  • 2020-12-21 09:22

    Your problem is not very well defined. Are empty sequences allowed or not? Shall [#] be related to [[],[]] (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).
    
    0 讨论(0)
  • 2020-12-21 09:25

    With meta-predicate splitlistIf/3 and the reified equality predicate (=)/3, the task at hand becomes a one-liner---that is both efficient and logically pure!

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

    As the code is monotone, logical soundness is ensured even for quite 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]].
    
    0 讨论(0)
提交回复
热议问题