4
$\begingroup$

Let say I have any expression

ex= f[h[r[x y]]] g[x z]

and I want to replace the x with w, but only for the x within the head f. Is there any simple way to do that?

Another, if I want to substitute an expression, say x, but only if it it is inside a pattern, say complicateExpression x, how can I do it? Of course, I can use the rule

complicateExpression x -> complicateExpression w

But this often means copy and paste complicateExpression

$\endgroup$
1
  • 2
    $\begingroup$ For the replacement of x inside f you could perhaps use a rule like {f[args__]:>f@@({args}/.{x->w})} $\endgroup$
    – Hausdorff
    Commented Jul 9, 2020 at 9:48

1 Answer 1

6
$\begingroup$
ex /. a_f :> (a /. x -> w)
 f[h[r[w y]]] g[x z]
ex2 = f[h[r[complicatedexpression  x ]]] g[x z];

ex2 /. ( p : complicatedexpression) x :> p w
f[h[r[complicatedexpression w]]] g[x z]
$\endgroup$
2
  • $\begingroup$ What if f is Inactive[f]? How to make that work? $\endgroup$ Commented Jul 9, 2020 at 12:19
  • 1
    $\begingroup$ @ablmf, something like ex4 = Inactivate[f[h[r[x y]]] g[x z], f]; ex4 /. a : (Inactive[f]@__) :> (a /. x -> w) or ex3 = Inactive[f][h[r[x y]]] g[x z]; ex3 /. a : (Inactive[f]@__) :> (a /. x -> w)? $\endgroup$
    – kglr
    Commented Jul 9, 2020 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.