2

This

h[g_, x_] := g[x]
h[Sqrt, x^2]

works obviously as well as :

f[x_]:= x^2
h[f,x]

but if

 k[x_] := Plot[x, {x, 0, 1}]   

 h[k,x] 

works but

 h[k, x^2]

since the substitution of $x^2$ is done also in the range. Is there a way to manage the substitution only partialy

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
cyrille.piatecki
  • 4,582
  • 13
  • 26
  • 2
    I wonder, how is Mathematica to know here that what you want is the x for the range, rather than, say, the 2 or the Power? How is it implemented in other languages? – Oleksandr R. May 09 '16 at 08:19

1 Answers1

4

Perhaps this will work for you in most cases:

kk[x_] :=
 With[{var = FirstCase[x, _Symbol, x, {-1}, Heads -> False]},
   Plot[x, {var, 0, 1}]
 ]

h[kk, 3 + x^2]

enter image description here

Notes:

  • Heads -> False is the default for FirstCase but it is more robust to include the option explicitly.

  • One might also use First @ Variables[x] in place of the FirstCase expression but there might be cases where FirstCase works better. While inadvisable this is valid input:

      Plot[2 Pi, {Pi, 0, 5}]
    

    yet First @ Variables[2 Pi] will throw an error message because Variables does not see Pi as a variable, but h[kk, 2 Pi] will still work with the code as written above.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • I do not underestand why in FirstCase[x, _Symbol, x, {-1}, Heads -> False] there is a second x and {-1}, But obviously, it works. – cyrille.piatecki May 09 '16 at 15:19
  • @cyrille.piatecki The third parameter is the default if no match is found, so I just used the given x expression in the event that FirstCase cannot find a _Symbol. {-1} is a levelspec -- please see (15567) for a better understanding. – Mr.Wizard May 10 '16 at 05:37