I want to replace all occurences of the symbol x with x[a], as long as it is not in the form x[a].
In other words, I am looking for magicReplacementRule in
x[a] + x /. magicReplacementRule
--> x[a] + x[a]
I tried
x[a] + x /. Except[x[a], x] -> x[a]
but the result was x[a][a] + x[a].
Answer
Use Replace instead of ReplaceAll with the option Heads -> False.
Replace[x[a] + x, x -> y, {0, Infinity}, Heads -> False]
{0, Infinity} here is a level specification which tells Replace to replace everywhere, just like ReplaceAll. You can drop Heads -> False because it's the default setting for Replace, but I wanted to point out the option which controls this behaviour.
Update: It appears that since version 10, All can be used as a substitute for the {0, Infinity} level specification:
Replace[x[a] + x, x -> y, All]
Comments
Post a Comment