From Mathematica's own documentation:
{g[1],Hold[g[1]]}/.g[n_]:>n+1
leads to
{2, Hold[1 + 1]}
My question: is there a way to protect subexpressions from being replaced by ReplaceAll? I am using composite constructs as variables, like
v[a, b]
and would like to be able to do stuff like this
v[a, b] + a - b /. {a -> x, b -> y}
leading to
v[a, b] + x - y
and not
v[x, y] + x - y
without complicated patterns. Unfortunately, using Replace and level specifications is not option.
This idiom
v[a, b] + a - b /. {catch_v -> catch, a -> x, b -> y}
works, as 'catch_v -> catch' prohibits the subsequent rules to be applied to v. But I would rather like to prohibit the replacement on the expression level (with some kind of Hold or HoldForm expression). Is this possible?
Since
ReplaceAll
is designed to "transform each subpart of an expression" and is often used specifically for the ability to operate inside ofHold
variations, you will need to use an inert form for your expression.One method is to convert your expression into a string. Here is an example:
Another method is to use
Compress
andUncompress
. This may prove more robust.I am not aware of anything like this "out of the box", but one can achieve a similar effect by hiding the expressions where one does not want replacements, with some temporary symbols, then applying the rules, and then restoring those expressions back. Here is one way:
Here is how one can use this:
I defined
ReplaceProtect
withUpValues
in a rather general way, so it can be used also withReplace
and other functions which use rules.