Prolog:获取并将列表中的每个第三项附加到新列表

时间:2016-02-08 02:14:02

标签: list prolog

使用Prolog中的以下代码,我设法从列表中提取每个第三项:

third([_,_,Z|L], Z).    
third([_,_,C|L], Y) :-
   third(L, Y).

但是,我仍然需要将我正在提取的每个项目追加到一个新列表中,最后创建一个仅包含" 每三个"项目。 我会感激任何提示或帮助! 谢谢。

4 个答案:

答案 0 :(得分:5)

这样做怎么样?

list_thirds([]        , []).
list_thirds([_]       , []).
list_thirds([_,_]     , []).
list_thirds([_,_,E|Es], [E|Xs]) :-
   list_thirds(Es, Xs).

使用SICStus Prolog 4.3.2的示例查询:

| ?- list_thirds([], Xs).
Xs = [] ? ;
no

| ?- list_thirds([a,b,c], Xs).
Xs = [c] ? ;
no

| ?- list_thirds([a,b,c,d,e,f], Xs).
Xs = [c,f] ? ;
no

| ?- list_thirds([a,b,c,d,e,f,g], Xs).
Xs = [c,f] ? ;
no

走向“其他方向”怎么样?

| ?- list_thirds(List, [x,y]).
List = [_A,_B,x,_C,_D,y]       ? ;
List = [_A,_B,x,_C,_D,y,_E]    ? ;
List = [_A,_B,x,_C,_D,y,_E,_F] ? ;
no                                     % terminates universally

最后,我们来看看我们从最常见的查询得到的答案序列:

| ?- list_thirds(Es, Xs).
Es = []                 , Xs = []      ? ;
Es = [_A]               , Xs = []      ? ;
Es = [_A,_B]            , Xs = []      ? ;
Es = [_A,_B,_C]         , Xs = [_C]    ? ;
Es = [_A,_B,_C,_D]      , Xs = [_C]    ? ;
Es = [_A,_B,_C,_D,_E]   , Xs = [_C]    ? ;
Es = [_A,_B,_C,_D,_E,_F], Xs = [_C,_F] ? ;
...

答案 1 :(得分:2)

使用SWI-Prolog和模块lambda.pl,您可以编写

:- use_module(library(lambda)).
third(In, Out) :-
    foldl(\X^Y^Z^(Y=[N,L],
              (   N = 2
              ->  append(L, [X], NL),
              Z = [0,NL]
              ;   N1 is N+1,
              Z = [N1, L])),
          In, [0, []], [_, Out]).

使用相同的查询:

 ?- third([1,2,3,4,5,6,7,8,9,10], Out).
Out = [3, 6, 9].

  ?- third(X, [3,6,9]).
X = [_G103, _G180, 3, _G352, _G438, 6, _G613, _G699, 9] ;
X = [_G103, _G180, 3, _G352, _G438, 6, _G613, _G699, 9|...] .

 ?- third(X, Y).
X = Y, Y = [] ;
X = [_G87231],
Y = [] ;
X = [_G87231, _G87317],
Y = [] ;
X = [_G87231, _G87317, _G87403],
Y = [_G87403] ;
X = [_G87231, _G87317, _G87403, _G87489],
Y = [_G87403] ;
X = [_G87231, _G87317, _G87403, _G87489, _G87575],
Y = [_G87403] ;
X = [_G87231, _G87317, _G87403, _G87489, _G87575, _G87661],
Y = [_G87403, _G87661] .

答案 2 :(得分:2)

有一种DCG方法也可以起作用,类似于@ repeat的答案:

thirds([]) --> [].
thirds([]) --> [_].
thirds([]) --> [_,_].
thirds([X|T]) --> [_,_,X], thirds(T).

或者更简洁(感谢@repeat):

thirds([]) --> [] | [_] | [_,_].
thirds([X|T]) --> [_,_,X], thirds(T).

如下所示:

| ?- phrase(thirds(T), [a,b,c,d,e,f,g,h]).

T = [c,f] ? a
no

| ?- phrase(thirds(T), L).

L = []
T = [] ? ;

L = [_]
T = [] ? ;

L = [_,_]
T = [] ? ;

L = [_,_,A]
T = [A] ? ;

L = [_,_,A,_]
T = [A] ? ;
...

答案 3 :(得分:1)

这将有效:

$(document).onload(function(){

//Type code here 
});

这会收集所有项目 bagof(Third,third(List,Third),Result). ,以使Third在列表中排名第三;并将它们的列表绑定到Third

有关行李的更多信息,请参阅npm-shrinkwrap.json