Is there parallel/simultaneous substitution in Mathematica?

I know this is simple but I’m not proficient at Mathematica and cannot seem to find it online or in the help. Also, Replace[] says it does the assignments in order, and instead of a complicated ternary-thing, I was hoping for something simple, to avoid a mistake.

I would like to make parallel, or simultaneous, substitutions. E.g. in Maxima:

(%i1) psubst ([a^2=b, b=a], sin(a^2) + sin(b));
(%o1) sin(b) + sin(a)
(%i2) subst ([a^2=b, b=a], sin(a^2) + sin(b));
(%o2) 2 sin(a)

Thank you all for answering my simple question!




Have you tried doing this in Mathematica though? ReplaceAll aka /. works just like this. Yes it does the assignments in order, but once a rule has been applied to a specific part, it won’t apply any other rules to that part.
– Marius Ladegård Meyer
May 31 at 21:19



Yes, I did this: Sin[a^2] + Sin[b] /. a^2 -> b /. b -> a but it gave me back 2 Sin[a]
– nate
May 31 at 21:27


1 Answer


You can achieve either result depending on the order of evaluation. As Marius pointed out, once a rule out of a set of rules has been applied to a specific part of an expression, no further rules will be applied to that expression.

Notice the difference between applying both rules at the same time, and applying them one after the other:

(* At the same time, only the first one applies *)
Sin[a^2] + Sin[b] /. {a^2 -> b, b -> a}
(* Out: Sin[a] + Sin[b] *)

(* One after the other *)
Sin[a^2] + Sin[b] /. a^2 -> b /. b -> a
(* Out: 2 Sin[a] *)

If you want a group of rules to be applied to an expression repeatedly until no further change is possible, then ReplaceRepeated (//.) will achieve that:

Sin[a^2] + Sin[b] //. {a^2 -> b, b -> a}
(* Out: 2 Sin[a] *)



Curly brackets! Thanks! I did note that if I change the order I get it right, but because my expression is extremely large I can’t visually check it. But this is much better than something like: Sin[a^2] + Sin[b] /. b -> A /. a^2 -> b /. A -> a
– nate
May 31 at 21:38



@nate Yes, you can reproduce any of those behaviors you mentioned at will, it’s just a question of choosing the right setup 🙂
– MarcoB
May 31 at 21:39