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

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

我需要在 prolog 中编写一个程序,它接受一个列表,反转该列表并将其附加到原始列表的末尾。

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

到目前为止我已经能够反转列表,但我可以设法将反转列表附加到原始列表。

这是我的资料:

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

你可以这样做:

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

在这里,首先使用 accumulatoraccRev 的第二个参数)反转列表,一旦完成,原始列表(保存在 [= 的第三个参数中) 11=]) 是前置的。

这是一个解决方案,可以在所有方向上正常工作

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

第二个参数将累积反向列表,第三个将累积结果:原始列表的每个元素都附加在第三个参数的开头,一旦我们清空它的尾部就是第二个参数第一个列表。

一些示例查询:

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