Say I have an expression (call it expr) involving a function, f[x]. I'd like to be able to evaluate that for a particular choice of f[x] without setting that choice for the whole session. I thought to do this using a replacement,

expr /. f[x_]->x^2

(where expr is some expression involving f[x] and I want to set f to x^2), but this doesn't work on derivatives, e.g., if expr contains f'[x] then it will stay as f'[x] rather than become 2x.

What's the best solution to this problem?

  • 1
    $\begingroup$ Check FullForm[f'[x]] to understand why, and figure out the appropriate replacement rule. $\endgroup$ Commented Jan 10, 2014 at 18:45
  • $\begingroup$ István - alright, I can see why it doesn't work, although I'm not sure how to construct a more general replacement rule. Still learning. Any hints? $\endgroup$
    – Adam
    Commented Jan 11, 2014 at 0:08
  • $\begingroup$ You can replace f by a pure function if you want things like derivatives to work. f->Function[x, x^2] $\endgroup$
    – Rojo
    Commented Jan 11, 2014 at 0:41
  • $\begingroup$ That's perfect!! That's the sort of simple solution I was hoping existed. If you write it as an answer I'll happily check it. If you or someone else wouldn't mind explaining, is there a reason to prefer either this solution or your Block solution? $\endgroup$
    – Adam
    Commented Jan 11, 2014 at 2:14
  • $\begingroup$ Adam you should ping with a @ the user you talk to. I hadn't seen this last comment of yours. Both work in this case, but the Block solution is slightly more general, and is the general solution for what you explicitly asked for: "evaluate something for a particular choice of some symbol without it affecting the whole session" $\endgroup$
    – Rojo
    Commented May 30, 2014 at 19:04

2 Answers 2


Using Block seems more appropriate

Block[{f}, f[x_]:=x^2;

Some different solutions to have this topic as a generic one:

expr = D[f[x y], x] + f[x, y]

expr /. f -> (#^2 &)
2 x + x^2

or more verbose:

expr /. f -> Function[x, x^2]
2 x + x^2

This functionality is also included in my dChange implementation from Analogue for Maple's dchange:

   f[x, y] == x^2
  • 1
    $\begingroup$ Thank you, this a nice solution! $\endgroup$
    – Dr_Zaszuś
    Commented Oct 17, 2017 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.