Strange substitution behavior in Mathematica

My question is: why the following does not work and how to fix it?

Plot[f[t], {t, 0, 2*Pi}] /. {{f -> Sin}, {f -> Cos}} 

The result is two empty graphs. For comparison,

 DummyFunction[f[t], {t, 0, 2*Pi}] /. {{f -> Sin}, {f -> Cos}} 

gives

 {DummyFunction[Sin[t], {t, 0, 2 *Pi}], DummyFunction[Cos[t], {t, 0, 2 * Pi}]} 

optional.

This is a simplified version of what I actually did. I was very annoyed that even after figuring out the annoying โ€œright wayโ€ to place curly braces, nothing worked.

In the end, I did the following, which works:

 p[f_] := Plot[f[t], {t, 0, 2*Pi}] p[Sin] p[Cos] 
+4
source share
3 answers

Mathematica tries to evaluate Plot before replacing. You can prevent this with the Hold and ReleaseHold functions:

 ReleaseHold[Hold[Plot[f[t],{t,0,2*Pi}]] /. {{f -> Sin},{f -> Cos}}] 

Holding [] will cause the entire Plot subexpression to fail during the substitution, then ReleaseHold [] will allow it to continue the actual construction.

+4
source

As an alternative to the Peter Hold / ReleaseHold strategy, you could do

 Plot[Evaluate[ f[t]/. {{f -> Sin}, {f -> Cos}} ], {t, 0, 2*Pi}] 

which is a little cleaner to read. This ensures that f replaced before Plot is evaluated.

+7
source

This is even shorter:

 Plot[#[t], {t, 0, 2*Pi}] & /@ {Sin, Cos} 
+7
source

Source: https://habr.com/ru/post/1304726/


All Articles