Questions on Mathematica's scoping constructs (Block, Module, With, etc.)

learn more… | top users | synonyms (1)

152
votes
7answers
7k views

What are the use cases for different scoping constructs?

Mathematica includes three functions that I know of which can be used to effectively (if not actually) define a variable and give it a value within a local scope: ...
59
votes
6answers
2k views

How to avoid nested With[]?

With[ {v1 = #}, With[ {v2 = f[v1]}, g[v1, v2] ] ] How to avoid nested With[] like the above? I'd like to use <...
40
votes
1answer
1k views

Local variables in Module leak into the Global context

From the Mathematica documentation on Module: Module allows you to set up local variables with names that are local to the module. But after using ...
39
votes
3answers
2k views

Why modules with no variables?

I was reading some code, in particular, recipe 4.13 on unification pattern-matching in Sal Mangano's Mathematica Cookbook, and there were many instances of Modules with no variables in them, such as ...
36
votes
4answers
950 views

Enforcing correct variable bindings and avoiding renamings for conflicting variables in nested scoping constructs

Using global variables the following turns an "expression" into a Function: expr = 2 x; Function[x, Evaluate[expr]] Of course ...
30
votes
1answer
409 views

What does Internal`InheritedBlock do?

What does the function Internal`InheritedBlock do? How is it different from the regular Block?
24
votes
2answers
1k views

What are some advanced uses for Block?

I read the answers to this question (What are the use cases for different scoping constructs?) and this one (Condition, Block, Module - which way is the most memory and computationally efficient?). ...
24
votes
1answer
616 views

Is the renaming mechanism of `With` flawed?

I'm confused about the renaming mechanism of With: ...
23
votes
1answer
228 views

Strange behavior with Cases and Position with SetDelayed

I feel like I must be missing something simple and obvious here, but this has me scratching my head. This works as expected: ...
22
votes
3answers
496 views

Nested definition: How can I define a function with a passed-in expression?

Here's a simplified version of what I'm trying to do: ...
20
votes
1answer
235 views

“With” as part of the “Dynamic Interactivity Language”

I noticed that in Mathematica's Function Navigator With is listed as being part of the "Dynamic Interactivity Language". It is not the first (or even the fourth, ...
19
votes
2answers
551 views

I define a variable as local to a module BUT then the module uses its global value! Why?

I have a question about modules and local variables. Here's my example: h = 5; Module[{a, h}, a[h_]= h^2; a[4]] (*Out[2] = 25*) I expected the module to ...
19
votes
0answers
262 views

Compile not correctly initializing a variable defined inside Module

Bug introduced in 8.0 and persisting through 10.3.1 or later In the following example, inside the minimumX's Module, ...
18
votes
1answer
258 views

A With expression local variable specification without head List

I just noticed a new form of With in its documentation: With[$x=x_0$, $expr$] specifies that all occurrences of the symbol $x$ in $expr$ should be replaced ...
17
votes
2answers
410 views

Messages leak out from Block

Bug introduced in 8.0 or earlier and fixed in 10.1 When assigning message to a symbol localized by Block, I would expect that this message is not accessible ...
17
votes
2answers
477 views

Module trash collection behaviour

I have asked this question before on the Wolfram community forum (http://community.wolfram.com/groups/-/m/t/83845?p_p_auth=Gxoxe65B) but not with great success. Module creates temporary variables of ...
16
votes
1answer
368 views

Modules that initialize themselves on first call

I use a lot of functions that extract a specific data item from a file with many data items. I want these functions to load data (slow) and return the item (fast) on first call, but just return the ...
15
votes
2answers
378 views

What is the purpose of Internal`LocalizedBlock?

I have come across the (internal) use of of the function: Internal`LocalizedBlock I am trying to determine its purpose. It seem to behave like ...
15
votes
3answers
619 views

Variable scope similar to other languages

Mathematica, unlike many other languages, defines the variables in the global scope unless it is explicitly asked to define a variable in a local scope, e.g., using ...
15
votes
1answer
420 views

Is the sharing of variables in Module/Block within Compile documented behavior?

Today I noticed something, I think for the first time. When used inside Compile variable values within Module (and ...
14
votes
3answers
275 views

How does $CellContext` work?

The only official info about $CellContext` I was able to find is: placeholder for the context of a symbol inside Dynamic ...
13
votes
4answers
362 views

Using With to scope over pure functions

Consider this example: given an option for a function func as "x" :> (a&), how can one assign different values to ...
13
votes
3answers
224 views

Internal DynamicModule steals scope of external DynamicModule

I have two dynamic objects, one nested in the other. Both have their own functions defined, as follows. I have simplified them to the point where they don't make much sense, but can still illustrate ...
13
votes
1answer
327 views

Is garbage collection broken in version 10.0.0?

Bug introduced in 10.0.0 and fixed in 10.0.1 In version 10.0.0 under Windows I am observing the following behavior: ...
12
votes
2answers
679 views

Syntax highlighter shows error for Manipulate when it's inside a Block or a Module

I'm putting my new copy of Mathematica 10 through its paces and I noticed a weird change in the colouring scheme that I find very annoying, and I'd like to get some insight into why it's happening. ...
12
votes
1answer
321 views

Context of localised (dynamic) symbols

When you localise a symbol with Module, the created unique symbol is usually in the current context. There seems to be an exception to this which has further ...
12
votes
1answer
253 views

Temporary variable not removed in Mathematica 10

Bug introduced in 10.0.1 and fixed in 10.0.2 In Mathematica 10, the documentation still states that a symbol with attribute Temporary will automatically be ...
12
votes
0answers
129 views

Integrate - Why is the integration variable not local

I have noticed something odd: Let f[t_]:=Integrate[x, {x, 0, t}] h[t_]:=Sum[x, {x, 0, t}] Now, enter ...
11
votes
2answers
1k views

Scoping in assigning a derivative

While answering another question, I stumbled upon a problem I cannot easily resolve. To assign the derivative of a function to another function, typically one can do this with a ...
11
votes
4answers
922 views

Subscripts - Why do I see the error “only assignments to symbols are allowed” when using a Module and not otherwise?

When I type Remove["Global`*"] foo[] := Module[{Subscript[a, 1] = "x"}, 0]; foo[] I get the expected error "only assignments to symbols are allowed". I ...
11
votes
3answers
987 views

What is the right way to construct DynamicModule

When I'm creating DynamicModules for CDF purposes I'm usualy basing on my experience with that, particular goal and content rather than on deep insight. I want to ...
11
votes
2answers
164 views

How to correctly implement in a new function the scoping behavior of Table, Sum and other commands that use Block to localize iterators?

It is documented that "Block is automatically used to localize values of iterators in iteration constructs such as Do, Sum, and Table." Therefore the dummy index (iterator) in a Sum is shielded ...
10
votes
2answers
308 views

Strange results while nesting scope constructs?

I did a handful of tests with Block, With, and Module and had a couple of new surprises. ...
10
votes
2answers
360 views

Avoiding MainEvaluate in a CompiledFunction to fetch global variables

I'm trying to write a simulation using Mathematica 8.0. Since I will most likely be doing the same operation over and over again, I'm trying to Compile whatever I ...
10
votes
2answers
372 views

Localizing variables within a Manipulate

I have a notebook with several examples of very similar computations, each involving the same variable/parameter names of the ingredients used in a final Manipulate....
10
votes
3answers
384 views

Find variable name from DumpSave on a scoped variable

I saved an InterpolationFunction in a ".mx" files using DumpSave on a variable that was scoped by a ...
10
votes
1answer
143 views

What are the scoping rules for function parameters shadowing System` symbols?

Here are some very contrived code snippets, highly unlikely to appear in real code, but still I am curious why they behave like this: ...
10
votes
1answer
145 views

Is it possible to use the global definition of a symbol as part of its new local definition set in a Block?

Consider the following expression: Block[{Print = CopyToClipboard}, doSomething[]] Now all calls to Print from ...
10
votes
0answers
589 views

Compile recursive function modifying global variables

How to compile recursive formula when it relies on more than a few global variables (global to the topmost compiled function)? It is unreasonable to pass on all such variables to each recursive ...
9
votes
4answers
583 views

How to set Block local variables by code?

I need to create a user-defined Block function where the Block variables' values are defined by code. For example, imagine I ...
9
votes
3answers
1k views

How to use local variables with indices in a Mathematica Block environment?

I have the following code: Subscript[f, i_][x_] := Block[{a}, Subscript[a, i] = 3 x; Subscript[a, 1] ] If I evaluate for example ...
9
votes
2answers
207 views

How to define UpValues in a different context from within a package

I'm trying to create a function (in a package) to import a lot of data and create a symbol with UpValues to return specific results about the data. I've got it working fine in a regular notebook, but ...
9
votes
1answer
307 views

Variable scoping in Module

I don't understand why $a$ and $b$ are not local in the following code: ...
9
votes
2answers
230 views

How to assemble and disassemble a function into steps

I've watched many programmers (both novice and expert) write functions in Mathematica and have observed a common behavioral pattern. This pattern has many elements that would be automated and thus ...
8
votes
3answers
175 views

With/Function(/etc) replacement behaviour

Can anyone explain to me this behaviour? I've been having more than a couple of similar doubts these last weeks. For example f[_?NumericQ] := 8; Now, if I do <...
8
votes
1answer
198 views

Why does the global variable exist here, where it was declared only in Module?

Why does Mathematica choose the mechanism that makes the global variable a here while parsing? In ...
8
votes
3answers
593 views

How do I avoid scoping collisions of iterator variables?

Yesterday I had an issue that kept for quite a while. My code wasn't producing the right results. Now I know why and I am wondering how to avoid the issue in future. Consider the following code. <...
8
votes
2answers
144 views

Question about scoping data in a multi-level Manipulate construction

Background: In a module containing an outer / inner manipulate I select the key of data with a dropdownlist in the outer manipulate. Data is read and displayed in the inner manipulate for edit ...
8
votes
1answer
795 views

Returning a value from a Module

In the following simple example MyMod := Module[{i}, Do[ Return[1], {i, 3} ]; Print["test"] ] I expected the module to exit on ...
8
votes
1answer
322 views

A smarter nested With?

I often find myself writing code that looks a bit like this: ...