1
$\begingroup$

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] 

[edit] : 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 ???

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

1 Answer 1

1
$\begingroup$

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.

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.