Consider:
expr /. (b[a_] * c_f /; !FreeQ[c, d[a]] :> (c /. (d[a] :> e) ))
Here's how it works: in expr
, the products b[a]*c
, with c
being a large arbitrarily deep expression with head f
, gets replaced with just c
in which all the d[a]
's replaced with e
. However, this replacement is supposed to happen only if the arbitrarily deep expression c
has at least one d[a]
in it.
But, I am afraid that the Condition
of !FreeQ[c,d[a]]
together with the second ReplaceAll
is making the pattern matcher/searcher scan through c
twice.
Is there a way to achieve this task by making the pattern matcher search through c
only once?
Follow up question: would it be any harder to achieve this task if the inner rule had more structure?
expr /. (b[a_] * c_f /; !FreeQ[c, d[___, a, ___]] :> (c /. (d[left___, a, right___] :> e[left, {b}, right]) ))
In this case d
is more complicated, and the replacement is more precise.
f
" I assume you actually meant "scan throughc
". Yes, it appears such a scan would recur. Why have theCondition
in the first place though? $\endgroup$b[a] f[(*stuff*)]
would unintentionally get transformed tof[(*stuff*)]
even if there is nod[a]
insidef[(*stuff*)]
. Theb[a]
pre-factor should disappear only if there isd[a]
insidef[(*stuff*)]
. $\endgroup$