Group Abstract Group Abstract

Message Boards Message Boards

18
|
17.8K Views
|
6 Replies
|
48 Total Likes
View groups...
Share
Share this post:

Scoping constructs in Wolfram Language

POSTED BY: Leonid Shifrin
6 Replies

With vs. Block example

One basic example that even new user often struggle is to insert values of parameters into an analytic solution. Let's say we have something like this

solution = DSolveValue[{y'[x] + y[x] == a Sin[x], y[0] == b}, y[x], x]

(* Out[1]= -(1/2) E^-x (-a - 2 b + a E^x Cos[x] - a E^x Sin[x]) *)

If you now want to insert values for a and b, the usual way is to use a replacement rule {a->aValue, b->bValue}. Nevertheless, users might try to insert values using

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

(* Out[6]= -(1/2) E^-x (-a - 2 b + a E^x Cos[x] - a E^x Sin[x]) *)

which fails. As Leonid already wrote With "does all the replacements before the body evaluates" and this makes the approach fail. Module cannot be used as well, because it uses lexical scoping that introduces new variable names that only look like normal a and b. Block, however, can be used

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

(* Out[7]= -(1/2) E^-x (-3 + E^x Cos[x] - E^x Sin[x]) *)

Although in general, using replacement rules is the better alternative, for some cases this gives a good alternative.

POSTED BY: Patrick Scheibe
POSTED BY: Daniel Lichtblau
Anonymous User
Anonymous User
Posted 9 years ago

For differentiating between With, Module, and Block, I find this example helpful (from the docs for With, "Examples", "Properties and Relations"):

In[1]:= {Block[{x = 5}, Hold[x]], With[{x = 5}, Hold[x]], Module[{x = 5}, Hold[x]]}
Out[1]= {Hold[x], Hold[5], Hold[x$119582]}
In[2]:= ReleaseHold[%]
Out[2]= {x, 5, 5}
POSTED BY: Anonymous User
POSTED BY: Leonid Shifrin

Thanks for sharing! very informational. I mostly use With/Module, Block very rarely. For the case of some (sub)routine, I found one generally uses Module over With because a routine generally has some temporary variable that needs to be stored/manipulated, so then one can only use Module (not With as the variables can not be manipulated).

POSTED BY: Sander Huisman
POSTED BY: Leonid Shifrin
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard