简体   繁体   English

列出序言中的连续对

[英]Make a list of consecutive pairs in prolog

I want to make a list of consecutive pairs from a given list, eg 我想从给定列表中列出连续对的列表,例如
given [1,2,3] it returns X=[[1,2],[2,3]] 给定[1,2,3]它返回X=[[1,2],[2,3]]
I'm a bit confused with the recursions. 我对递归有点困惑。
I tried with the code above, it returns me the pairs (one at a time) but the append doesn't work. 我尝试使用上面的代码,它返回给我一对(一次一对),但附加项不起作用。

pair_list([X,Y|_], [X,Y]):- 
  append([[X,Y]],[,],L),
  write(L). 

pair_list([_|Tail], XY):- 
  pair_list(Tail,XY).

Learning recursion is essential, so go with damianodamiano' answer. 学习递归是必不可少的,所以请跟达米亚诺达米亚诺的答案一起去。 Then consider the basic 'all solutions' tools, like findall/3: 然后考虑基本的“所有解决方案”工具,例如findall / 3:

?- L=[1,2,3],findall([X,Y],append(_,[X,Y|_],L),Ps).
L = [1, 2, 3],
Ps = [[1, 2], [2, 3]].

First, let's consider the following points: 首先,让我们考虑以下几点:

  • A clean representation of pairs is important. 对的清晰表示重要。

    • Do not use "comma lists" [A,B] or "comma pairs" (A,B) . 不要使用“逗号列表” [A,B]或“逗号对” (A,B)

    • Instead, use compound terms having the form AB . 而是使用AB形式的复合词。

  • Stick to the logically pure subset of Prolog for maximum code versatility. 坚持Prolog的逻辑纯子集,以实现最大的代码多功能性。

A straightforward implementation goes like this: 一个简单的实现是这样的:

list_adjitems([], []).
list_adjitems([E|Es], Xs) :-
   list_adjitems_previous(Es, Xs, E).

list_adjitems_previous([], [], _).                    % auxiliary predicate
list_adjitems_previous([E1|Es], [E0-E1|Xs], E0) :-
   list_adjitems_previous(Es, Xs, E1).

Some sample queries: 一些示例查询:

?- list_adjitems([], Xs).
Xs = [].

?- list_adjitems([a], Xs).
Xs = [].

?- list_adjitems([a,b,c], Xs).
Xs = [a-b,b-c].

Does this work in the "reverse" direction, too? 这也可以在“反向”方向上工作吗? (Hint: it does.) (提示:是的。)

?- list_adjitems(Es, []).
   Es = []
;  Es = [A].

?- list_adjitems(Es, [x-y,y-z,z-u,u-v]).
Es = [x,y,z,u,v].

Last, let's not forget about the most general query : 最后,我们不要忘记最一般的查询

?- list_adjitems(Es, Xs).
   Es = []             , Xs = []
;  Es = [A]            , Xs = []
;  Es = [A,B]          , Xs = [A-B]
;  Es = [A,B,C]        , Xs = [A-B,B-C]
;  Es = [A,B,C,D]      , Xs = [A-B,B-C,C-D]
;  Es = [A,B,C,D,E]    , Xs = [A-B,B-C,C-D,D-E]
;  Es = [A,B,C,D,E,F]  , Xs = [A-B,B-C,C-D,D-E,E-F]
;  Es = [A,B,C,D,E,F,G], Xs = [A-B,B-C,C-D,D-E,E-F,F-G]
…                                                     % ... and so on ...

Works just like it should™. 发挥应有的作用™。

Homework: re-run above queries with the code proposed in the other answers! 作业:使用其他答案中提出的代码重新运行以上查询!

Simply write: 只需写:

pair([_],[]).
pair([A,B|T],[[A,B]|T1]):-
    pair([B|T],T1).

Query: 查询:

?-pair([1,2,3],L).
L = [[1, 2], [2, 3]]

You don't need to use append/3 . 您不需要使用append/3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM