根据另一个列表给出的索引交换元素

Swapping elements based on index given from another list

你好,我的任务是交换列表的元素,以及需要在另一个列表中交换的索引,所以 fx:

如果我有:

[3,1,2] as the list

并且:

[[1,2],[2,3]] as the index that needs to be swapped

然后它应该是这样的:

[1,2] = 3 and 1 getting swapped
[2,3] = 3 and 2 getting swapped

所以我最终会得到 Output = [1,2,3]

谓词指定如下:

swap(C,Input,Output)

其中 C 是应该交换的元素列表。

输入是应该交换的列表。

输出是交换后的列表。

我想要一些关于如何基于此交换这些元素的建议,我已经看过这个:swap two elements from list with specified indices

希望有人能帮助我。

编辑:

到目前为止我已经尝试过这样的事情:

swap( Input,[I|J], Input ) :-
    I = J.
swap( Input, [I|J], Output ) :-
    swap( Input, [I|J], Output, _, _ ).
swap( Input, [I|J], Output ) :-
    swap( Input, J, I, Output, _, _ ).

swap( [E2|Ls], I,  0,  [E1|Ls], E1, E2 ):-!.
swap( [E1|Es], 0, J, [E2|Rs], E1, E2 ) :-
    N2 is J - 1,
    swap( Es, -1, N2, Rs, E1, E2 ),!.
swap( [E|Es], [I|J], [E|Rs], E1, E2 ) :-
    N1 is I - 1,
    N2 is J - 1,
    swap( Es, N1, N2, Rs, E1, E2 ). 

但我只能使用 "one" 列表作为必须交换的索引,例如 [1,2],我正在寻找的是能够使用多个 [[ 1,2],[2,3]] 等等。

使用list_i_j_swapped/4

list_i_j_swapped(As,I,J,Cs) :-
 same_length(As,Cs),
 append(BeforeI,[AtI|PastI],As),
 append(BeforeI,[AtJ|PastI],Bs),
 append(BeforeJ,[AtJ|PastJ],Bs),
 append(BeforeJ,[AtI|PastJ],Cs),
 length(BeforeI,I),
 length(BeforeJ,J).

swap(List,[],List).
swap(List1,Swaps,ListSwapped):-
  Swaps =[[Index1,Index2]|T],
  list_i_j_swapped(List1,Index1,Index2,List2),
  swap(List2,T,ListSwapped).

问:

?- swap([3,1,2],[[0,1],[1,2]],X).
X = [1, 2, 3] ;
false.

位置为零索引。

此答案基于

+ 变体来了!

:- use_module(library(lambda)).

swap2(Ls0, Swaps, Ls) :-
   foldl(\[I,J]^S0^S^list_i_j_swapped(S0,I,J,S), Swaps, Ls0,Ls).

示例查询:

?- swap2([3,1,2], [[0,1],[1,2]], Xs).
  X = [1,2,3]
; false.