简体   繁体   English

如何在Prolog中反转列表并将两个列表连接在一起

[英]How to reverse a list and join two lists together in prolog

I need to write a program in prolog that accepts a list, reverses that list and the appends that to the end of the original list. 我需要在prolog中编写一个程序,该程序接受一个列表,反转该列表,并将其追加到原始列表的末尾。

Example: list_rList([1,2,3],X) 示例:list_rList([1,2,3],X)
X = [1,2,3,3,2,1] X = [1,2,3,3,2,1]

So far I have been able to reverse the list, but I can manage to append the reverse list to the original list. 到目前为止,我已经可以反转列表,但是我可以设法将反转列表附加到原始列表中。

Here is what I have: 这是我所拥有的:

list_rList([],[]).  
list_rList([H|T],R):-  list_rList(T,RevT),  append(RevT,[H],R).

Here is a solution which will work correctly in all directions : 这是一个可以在所有方向正常工作的解决方案:

list_rList(L, T) :-
    list_rList(L, [], T).

list_rList([], A, A).
list_rList([H|T], C, [H|T2]) :-
    list_rList(T, [H|C], T2).

The second argument will accumulate the reversed list, and the third one will accumulate the result: each element of the original list is appended at the beginning of that third argument, and its tail is the second argument once we have emptied the first list. 第二个参数将累加反向列表,第三个参数将累加结果:原始列表的每个元素都附加在第三个参数的开头,一旦我们清空了第一个列表,它的尾部就是第二个参数。

Some example queries: 一些示例查询:

?- list_rList([1,2,3],Z).            % What you asked
Z = [1, 2, 3, 3, 2, 1].

?- list_rList([1|T],Z).              % With a variable tail
T = [],
Z = [1, 1] ;
T = [_G1659],
Z = [1, _G1659, _G1659, 1] ;
T = [_G1659, _G1668],
Z = [1, _G1659, _G1668, _G1668, _G1659, 1]
…

?- list_rList(Z,[1,2,3,3,2,1]).      % The original list from the result
Z = [1, 2, 3] ;
false.

?- list_rList(Z,[1,2,3,3,2]).        % Check that a list can be the result of this predicate
false.

?- list_rList(Z,[1,2,3,X,Y,3,2,1]).  % With variable elements in the result
Z = [1, 2, 3, Y],
X = Y ;
false.

?- list_rList(L,Z).                  % With completely free arguments
L = Z, Z = [] ;
L = [_G1623],
Z = [_G1623, _G1623] ;
L = [_G1623, _G1632],
Z = [_G1623, _G1632, _G1632, _G1623] ;
L = [_G1623, _G1632, _G1641],
Z = [_G1623, _G1632, _G1641, _G1641, _G1632, _G1623] ;
L = [_G1623, _G1632, _G1641, _G1650],
Z = [_G1623, _G1632, _G1641, _G1650, _G1650, _G1641, _G1632, _G1623]
…

you could do something like this: 您可以执行以下操作:

accRev([H|T],A,L,R) :-  accRev(T,[H|A],L,R).
accRev([],A,L,R) :- append(L,A,R).

list_rList(L,R) :- accRev(L,[],L,R).

Here, first the list is reversed using an accumulator (the second argument of accRev ) and once this is finished, the original list (which is kept in the third argument of accRev ) is prepended. 在这里,首先使用累加器accRev的第二个参数)对列表进行反转,完成后,将添加原始列表(保留在accRev的第三个参数中)。

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

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