# Swap two elements in a list in a recursive manner

I have a function which takes a list as an argument, and I have to swap two precise elements of the list. My call is of the form

f[h1_,{n1___}] :=


I need that under a certain test which will be an a If statement, two precise elements of n1 are switched. I may therefore need a Module to store the intermediate list and call my function f with the new list. I checked Swapping elements of list and Swap elements in list without copy but in both those questions, the proposed function never return the desired list but just modify the actual list.

f[h1_,{n1___}] = If[test=True,f[h1,{swappedN1}],ElseStatement]


I therefore need a function that makes

swap[{1,2,3,4},1,2] -> {2,1,3,4}


such that I can do something like

 f[h1_,{n1___}] = If[test=True,f[h1,swap[{n1},pos1,pos2],ElseStatement]


Is that possible in Mathematica ?

Just use a temporary variable:

swap[a_List, p_, q_] := Module[{aa = a}, aa[[{p, q}]] = aa[[{q, p}]]; aa]

swap[{1, 2, 3, 4}, 1, 2]

{2, 1, 3, 4}


Actually I just remembered there is a built-in for this: Permute with Cycles

Permute[{1, 2, 3, 4}, Cycles[{{1, 2}}]]

{2, 1, 3, 4}


Also ReplacePart is rather clean:

swap[a_, p_Integer, q_Integer] := ReplacePart[a, {p -> a[[q]], q -> a[[p]]}]

• Nice, thank you very much ! Mar 12, 2017 at 14:04