3
$\begingroup$

Suppose, there are two delayed expressions

D1:= RandomVariate[UniformDistribution[{-1, 0}]];
D2:= RandomVariate[ UniformDistribution[{0, 1}]];

D1, D2 work as needed generating a pair of random numbers. How to swap D1, D2 without repeating the full coding

D2:= RandomVariate[UniformDistribution[{-1, 0}]];
D1:= RandomVariate[ UniformDistribution[{0, 1}]];

Clearly, that code {D1,D2}= (or :=) {D2,D1} does not work.

$\endgroup$
6
$\begingroup$

There are different usages of SetDelayed. Read SetDelayed documentation, Section Scope > Diffrent Kinds of Values for more information.

This solution works on var := def (like your case) not var[] := def or other kinds.

Code

ClearAll[swapSetDelays];

SetAttributes[swapSetDelays, HoldAll];

swapSetDelays[a_, b_] := With[{temp = OwnValues[a]},
  OwnValues[a] = OwnValues[b] /. HoldPattern[b] :> a;
  OwnValues[b] = temp /. HoldPattern[a] :> b;
  ]

Example

SeedRandom[1];

r1 := RandomInteger[{1, 10}];
r2 := RandomInteger[{11, 20}];

{r1, r2}
(* Out: {2,15} *)

swapSetDelays[r1, r2];

{r1, r2}
(* Out: {11, 8} *)
$\endgroup$
3
  • $\begingroup$ +1 (but strictly, more clever than useful) $\endgroup$
    – mikado
    Jun 4 '21 at 18:10
  • $\begingroup$ @mikado thanks for your feedback but I should confess that the idea came from OwnValues Neat Examples 🤫. $\endgroup$
    – Ben Izd
    Jun 4 '21 at 18:21
  • $\begingroup$ This works fine Thanks $\endgroup$
    – Konstantin
    Jun 4 '21 at 18:29
4
$\begingroup$

In the rather unlikely case of you actually wanting to swap two definitions, e.g.

D1 := RandomVariate[UniformDistribution[{-1, 0}]];
D2 := RandomVariate[UniformDistribution[{0, 1}]];

You can do so temporarily

Module[{D1 = D2, D2 = D1}, Print[{D1, D2}]]
{0.863742,-0.710931}

If you've already used these definitions e.g.

print := Print[{D1, D2}]
print
{-0.349444,0.720738}

and would like to interchange them temporarily, you can use

Block[{D1 = D2, D2 = D1}, print]
{0.123198,-0.592611}

Needless to say, if you interchange them permanently, there is risk of becoming confused about how many times you've done it!

$\endgroup$
3
$\begingroup$

Can't you just define a single function?

d[x_,y_]:=RandomVariate[UniformDistribution[{x, y}]];

Then call it as:

D1 = d[-1,0]

or

D2 = d[0,1]
$\endgroup$
1
  • $\begingroup$ Yeah, this possible, but not very fit to my purpose $\endgroup$
    – Konstantin
    Jun 4 '21 at 18:20

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.