Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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
1  
Check FullForm[f'[x]] to understand why, and figure out the appropriate replacement rule. –  István Zachar Jan 10 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 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 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 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 at 19:04

1 Answer 1

up vote 9 down vote accepted

Using Block seems more appropriate

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

Your Answer

 
discard

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.