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.

  • 2
    $\begingroup$ Use Block instead. $\endgroup$
    – Kuba
    Commented Feb 10, 2014 at 11:49
  • $\begingroup$ You might be interested in Leonid Shifrin's answer to this question $\endgroup$
    – user1066
    Commented Feb 10, 2014 at 20:00

1 Answer 1


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;

Another option is to use Block, which does dynamic scoping

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

More info here.

  • $\begingroup$ Didn't feel the need to post a seperate A. Hope you don't mind. $\endgroup$
    – Ajasja
    Commented Feb 10, 2014 at 12:08
  • 1
    $\begingroup$ 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. $\endgroup$
    – ac1965
    Commented Feb 10, 2014 at 12:20
  • $\begingroup$ @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. $\endgroup$ Commented Feb 10, 2014 at 13:14
  • $\begingroup$ @Alberto, what you are describing is dynamic scoping, and Block is what does that. With is for a different purpose $\endgroup$
    – Rojo
    Commented Feb 10, 2014 at 13:41
  • 1
    $\begingroup$ 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) $\endgroup$
    – ac1965
    Commented Feb 10, 2014 at 16:46

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