# Problem with With [duplicate]

This question already has an answer here:

I am puzzled byWith. it does not seem to work. Please see example below (I have also used Evaluate and N on it, to no avail).

force[x_] := a x - b x^3

With[{a = 1, b = 1}, force[1]]

a - b


Being naive, I would expect to see 0 as a result; a and b should have been transformed into 1 by With.

-

## marked as duplicate by Mr.Wizard♦Feb 10 at 14:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

Use Block instead. –  Kuba Feb 10 at 11:49
You might be interested in Leonid Shifrin's answer to this question –  TomD Feb 10 at 20:00

## 1 Answer

With replaces occurrences of declared constants with their values, but it won't change the definition of force[] outside its scope. To do that you'd need to include the function definition like so :-

With[{a = 1, b = 1},
force[x_] := a x - b x^3;
force[1]]

0


Another option is to use Block, which does dynamic scoping

Block[{a = 1, b = 1}, force[1]]

0


More info here.

-
Didn't feel the need to post a seperate A. Hope you don't mind. –  Ajasja Feb 10 at 12:08
Thank you - the first solution is too cumbersome, would mean repeating definitions. I was aware of Block and Module, but I read that With is much faster, so I was hoping to use that. I must say I still do not understand why With does not change a and b inside force for the purpose of this calculation: it wouldnt mean changing it inside the definition of force, just for this evaluation. –  Alberto Feb 10 at 12:20
@Alberto - In your original form the definition of force[] can be found in DownValues@force. With simply doesn't affect that definition, being defined outside its scope. –  Chris Degnen Feb 10 at 13:14
@Alberto, what you are describing is dynamic scoping, and Block is what does that. With is for a different purpose –  Rojo Feb 10 at 13:41
I see - speed actually could be an issue as this is going to go inside a montecarlo. Thanks for your help (I still think the behaviour is counterintuitive - but alas this is often the price to pay for Mathematica's advantages) –  Alberto Feb 10 at 16:46