In mathematics, a given operation $\circ$ is said to be associative if there is equality $$(f\circ g)\circ h=f\circ(g\circ h)$$ for any $f$, $g$ and $h$. Intuitively, this means that parentheses don't matter when one is dealing with the given operation.

I'm wondering if Mathematica's ReplaceAll operator /. is associative. Explicitly, suppose that expr1 is an expression, and expr2 and expr3 are replacement rules. Will the Mathematica kernel distinguish between the inputs (expr1 /. expr2 ) /. expr3 and expr1 /. (expr2 /. expr3 )?

Here is an example, which evaluates to True:

(x /. x -> y) /. y -> z == x /. (x -> y /. y -> z)

Is there a nice example of ReplaceAll behaving in a non-associative manner? Can I expect associativity under reasonable conditions? What if we consider the ReplaceRepeated operator //. instead of /.?

  • $\begingroup$ @Kuba - beat me by seconds. Regarding the LHS, there are also various options. One could execute the x->z replacement first. The replacement operator take three arguments after all. $\endgroup$
    – LLlAMnYP
    Nov 20, 2015 at 8:47
  • $\begingroup$ Using the Extend Selection functionality of the front end, one can see that /. is left-associative btw... $\endgroup$
    – sebhofer
    Nov 20, 2015 at 12:29

1 Answer 1


This question has a trivial answer, ReplaceAll is not associative!

( x + y /. x -> y ) /. y -> z

resulting in



x + y /. (x -> y /. y -> z)


Same is true for ReplaceRepeated.

  • $\begingroup$ As associativity is normally defined as a property of a binary relation I think it would be nicer to have an example such as x + y /. x -> y /. y -> z, which of course shows exactly the same behaviour... $\endgroup$
    – sebhofer
    Nov 20, 2015 at 12:26

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.