# Replace an If by a combination using replacement rules

Consider the following code :

tttest = a^2 + If[a > 0, a, -a]

a^2 + If[a > 0, a, -a]


I would like to replace my If function by something like fonction @ If. I did the following, but the replacement doesn't occur.

Replace[tttest, If -> (fonction @ If)]

a^2 + If[a > 0, a, -a]


How to make the replacement working and why isn't it working here ? For me it is an example of the same kind as the one in the documentation :

Replace[x^2, x^2 -> a + b]


 : as suggested by the comment, I switched to ReplaceAll and I wrote the following : (the example is slightly different)

    ReplaceAll[If[lambda + lambdaBis != 0, PM[m] Log[PM[m]], 0],
If[x1_, x2_, x3_] -> fonction [If[x1, x2, x3]]]

fonction[If[lambda + lambdaBis != 0, PM[m] Log[PM[m]], 0]]


And here it works.

However, I want to actually simplify an expression linked to this question I asked Why is the function assuming not taken in consideration?

I did the following :

 Assuming[lambda00 > 0 && lambda00Bis ,


ReplaceAll[If[lambda + lambdaBis != 0, PM[m] Log[PM[m]], 0], If[a1_, a2_, a3_] -> (gggg [If[a1, a2, a3]])]]

gggg[If[lambda + lambdaBis != 0, PM[m] Log[PM[m]], 0]]

Here everything shows up correctly, but if actually my function gggg is Simplify, nothing is simplified (so the function "doesnt work" here).

Assuming[lambda00 > 0 && lambda00Bis ,
ReplaceAll[If[lambda + lambdaBis != 0, PM[m] Log[PM[m]], 0],
If[a1_, a2_, a3_] -> (Simplify [If[a1, a2, a3]])]]

If[lambda + lambdaBis != 0, PM[m] Log[PM[m]], 0]


Why ???

• Use ReplaceAll.
– Alan
Commented Dec 30, 2018 at 16:13
• Or you can Replace[tttest, If -> (fonction@If), Infinity, Heads -> True]
– Alan
Commented Dec 30, 2018 at 16:19
• @Alan I edited my message Commented Dec 30, 2018 at 16:24
• About your edit: use RuleDelayed.
– Alan
Commented Dec 30, 2018 at 16:55

You are trying to match an expression with Head If. Therefore you need to use a pattern that will match that expression head. See the Patterns tutorial. You should also make use of RuleDelayed since you need to reference a named pattern from your replacement rule.

With

tttest = a^2 + If[a > 0, a, -a];


Then

tttest /. if_If :> fonction@if

a^2+fonction[If[a>0,a,-a]]


Hope this helps.