Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 过滤器列表序言_List_Prolog_Logical Purity - Fatal编程技术网

List 过滤器列表序言

List 过滤器列表序言,list,prolog,logical-purity,List,Prolog,Logical Purity,我试图在prolog中筛选列表列表,以便[[a,b,c],[d],[e,f]]给出[[a,b,c],[e,f]],我的筛选函数应该忽略长度小于2的元素, 我试过的代码如下: omitunwanted([],_) :- []. omitunwanted([List|L1],[H|T]) :- ( length(List,0)-> omitunwanted(L1,[H|T]) ; length(List,1)-> omitunwanted(L1,

我试图在prolog中筛选列表列表,以便[[a,b,c],[d],[e,f]]给出[[a,b,c],[e,f]],我的筛选函数应该忽略长度小于2的元素, 我试过的代码如下:

omitunwanted([],_) :- [].
omitunwanted([List|L1],[H|T]) :-
   (  length(List,0)->
      omitunwanted(L1,[H|T])
   ;  length(List,1)-> 
      omitunwanted(L1,[H|T])
   ;  append(List,[],H), 
      omitunwanted(L1,T)
   ).

它返回输入[[a,b,c],[e,f]| U G1622]的输出[[a,b,c],[d],[e,f]]。我想不出我做错了什么

考虑使用
exclude/3
。例如:

length_less_than_two(Ls) :-
    must_be(list, Ls),
    length(Ls, L),
    L < 2.

这里有一个纯版本,它甚至适用于@mat的版本产生干净的
实例化\u错误的情况

length_less_than_two_truth([],  true).
length_less_than_two_truth([_],  true).
length_less_than_two_truth([_,_|_], false).

texclude(     _, [], []).
texclude(CT, [E|Es], Fs0) :-
   call(CT,E,Truth),
   (  Truth = true,
      Fs0 = Fs
   ;  Truth = false,
      Fs0 = [E|Fs]
   ),
   texclude(CT, Es, Fs).

?- texclude(length_less_than_two_truth, [X,[a,b,c]],Ls).
X = [],
Ls = ["abc"] ;
X = [_A],
Ls = ["abc"] ;
X = [_A, _B|_C],
Ls = [[_A,_B|_C], "abc"] ;
false.

在这个答案中,我们使用与之相同的行

作为一个起点,考虑下面的查询:

?- texclude(length_less_than_two_truth, [[a,b,c],[],[d],[e,f]], Xs). Xs = [[a,b,c],[e,f]] % succeeds, but leaves choicepoint behind ; false. 请注意,
length\u less\u than\u two\u t/2
的第二个子句基于

通过此实现,让我们重新运行OP在问题中给出的查询:

?- texclude(length_less_than_two_t, [[a,b,c],[],[d],[e,f]], Xs). Xs = [[a,b,c],[e,f]]. % succeeds deterministically ?-t包括(长度小于两个t,[[a,b,c],[d],[e,f]],Xs)。 Xs=[[a,b,c],[e,f].%决定性地成功
在这种情况下,
必须是
确保列表被充分实例化,以便我们能够可靠地决定是否排除它。如果您忽略了
必须/2
目标,您将做出错误的决定,例如当列表为
[X、[a、b、c]
时。
texclude(P_2,Es,Fs) :-
   list_texclude_(Es,Fs,P_2).

list_texclude_([],[],_).
list_texclude_([E|Es],Fs0,P_2) :-
   if_(call(P_2,E), Fs0 = Fs, Fs0 = [E|Fs]),
   list_texclude_(Es,Fs,P_2).

length_less_than_two_t([],true).
length_less_than_two_t([_|Es],T) :-
   =(Es,[],T).
?- texclude(length_less_than_two_t, [[a,b,c],[],[d],[e,f]], Xs). Xs = [[a,b,c],[e,f]]. % succeeds deterministically