Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
Check FullForm[f'[x]] to understand why, and figure out the appropriate replacement rule. – István Zachar Jan 10 '14 at 18:45
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? – Adam Jan 11 '14 at 0:08
You can replace f by a pure function if you want things like derivatives to work. f->Function[x, x^2] – Rojo Jan 11 '14 at 0:41
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? – Adam Jan 11 '14 at 2:14
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" – Rojo May 30 '14 at 19:04
up vote 12 down vote accepted

Using Block seems more appropriate

Block[{f}, f[x_]:=x^2;
share|improve this answer

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
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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