5
$\begingroup$

Often I have to do perform a succession of substitutions on some expression, and in a notebook the way I know to do that is

((((expr /. subst1) /.subst2) /.subst3) ...

So everytime I want to add a substitution I have to go back at the beginning of the line and add a ( and then go at the end of the line and add a ) and then put the new substitution. Is there a more comfortable way to do that? Something like

expr // function1 // function2 // function3 ...

On the same line, when I have to both apply functions and substitution I have to use again the brackets, because

expr // function1 /. subst1 // function2...

mess up the order in which things are done: function2 is applied to subst1 which is then applied to function1 which is then applied to expr.

$\endgroup$
  • 2
    $\begingroup$ ReplaceAll has an operator form. expr // ReplaceAll[expr -> 1] // ReplaceAll[1 -> 2] $\endgroup$ – Kuba Oct 24 '18 at 12:03
  • 3
    $\begingroup$ You don't need any of those parentheses, since /. is already left associative. Just use expr /. subst1 /.subst2 /.subst3. $\endgroup$ – Carl Woll Oct 24 '18 at 14:25
  • 2
    $\begingroup$ you might find Fold convenient: e.g., substitutions = {a -> 1, b -> d, c -> 2, d -> 3}; Fold[ReplaceAll, {a, b, c, d}, substitutions] . $\endgroup$ – kglr Oct 24 '18 at 16:50
  • 1
    $\begingroup$ Note that replacement can take list arguments, so if the substitutions are independent you could write expr/.{subst1,subst2,subst3}. It they are not independent, expr//.{subst1,subst2,subst3} might give you the answer you need. $\endgroup$ – mikado Oct 24 '18 at 17:12
3
$\begingroup$

Summing up, this is perfectly fine:

2 /. 2->{2,3} /. 2 -> 4

{4, 3}

And if you need to mix it with functions you can use an operator form of ReplaceAll:

4 // Sqrt // ReplaceAll[2 -> 5]

5

$\endgroup$

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.