将列表过滤到单独的列表中

时间:2014-10-18 11:04:43

标签: list prolog prolog-dif

我需要过滤列表[#,d,e,#,f,g],以便将输出设为[[d,e],[f,g]]
每次遇到'#'时我都会在创建新列表时遇到困难有没有办法做到这一点? 我尝试了下面的代码,

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

3 个答案:

答案 0 :(得分:4)

您的问题定义不明确。是否允许空序列?应该[#][[],[]](之前和之后有空序列)或[]相关联吗?你说它应该是[]。所以:

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).

答案 1 :(得分:3)

这是另一个版本,它使用更通用的方法:

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([], []).

使用lambdas,可以更紧凑地表达。而不是

   all_seq(callfalse(C_2),Xs)

callfalse/3的定义,现在可以写

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

答案 2 :(得分:2)

使用元谓词splitlistIf/3和具体化的等式谓词(=)/3,手头的任务变成了单行 ---既有效又逻辑纯净

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

由于代码单调,即使是非常一般的查询,也可以确保逻辑健全:

?- 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]].