1
$\begingroup$

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 ?

$\endgroup$
3
$\begingroup$

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]]}]
$\endgroup$
  • $\begingroup$ Nice, thank you very much ! $\endgroup$ – Ezareth Mar 12 '17 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.