2
$\begingroup$

Suppose I have some rule, e.g. Re[x_] :> (x + Conjugate[x])/2. I want to apply it to all matching sub-expressions in some expression, excluding any sub-expressions that are located somewhere under heads Hold[…] or Function[…] (at any depth). What is the simplest way to do that? Can it be done without explicit filtering of positions?


For example, the result of replacement in the expression:

{z + Re[a], Hold[1 + Re[b]], Function[z, Abs[Re[c]]]}

should be

{z + (a + Conjugate[a])/2, Hold[1 + Re[b]], Function[z, Abs[Re[c]]]}

where Re[b] and Re[c] are left unmodified, because they are located under Hold and Function.

$\endgroup$
  • $\begingroup$ Vladimir, an example of some expression would make it so much easier to answer your question. $\endgroup$ – kglr Sep 1 at 1:44
  • 1
    $\begingroup$ It seems that my question is a duplicate of stackoverflow.com/q/6451802/305118 $\endgroup$ – Vladimir Reshetnikov Sep 1 at 2:43
3
$\begingroup$

Just include the patterns you want to avoid in your replacement rule:

ReplaceAll[
    {z + Re[a], Hold[1 + Re[b]], Function[z, Abs[Re[c]]]},
    {
        h:(_Hold | _Function) :> h,
        Re[x_] :> (x+Conjugate[x])/2
    }
]

{z + 1/2 (a + Conjugate[a]), Hold[1 + Re[b]], Function[z, Abs[Re[c]]]}

$\endgroup$

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.