17

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?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Adam
  • 709
  • 6
  • 11
  • 1
    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 00: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 00: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 02: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

2 Answers2

16

Using Block seems more appropriate

Block[{f}, f[x_]:=x^2;
expr]
Rojo
  • 42,601
  • 7
  • 96
  • 188
13

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:

dChange[
   expr,
   f[x, y] == x^2
]
Kuba
  • 136,707
  • 13
  • 279
  • 740