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

learn more… | top users | synonyms (1)

93
votes
7answers
3k 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: ...
34
votes
3answers
1k 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 ...
32
votes
4answers
785 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 ...
23
votes
4answers
446 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 ...
23
votes
1answer
218 views

What does Internal`InheritedBlock do?

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

What are some advanced uses for Block?

I read the answer to this question and this one. According to those, Block is safer (if something aborts, it restores the values) and faster (perhaps something to ...
18
votes
1answer
201 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, ...
14
votes
2answers
229 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 ...
14
votes
1answer
274 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 ...
12
votes
3answers
294 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 ...
12
votes
1answer
275 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 ...
11
votes
4answers
299 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 ...
10
votes
2answers
464 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 ...
10
votes
2answers
361 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. ...
10
votes
2answers
226 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 ...
9
votes
2answers
227 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. ...
9
votes
3answers
806 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
260 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 ...
9
votes
3answers
275 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 ...
9
votes
1answer
122 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: ...
9
votes
0answers
108 views

Is garbage collection broken in version 10.0.0?

In version 10.0.0 under Windows I am observing the following behavior: Do[Module[{foo}, foo[x_] := 1; foo[0]], {10}] Names["foo$*"] ...
9
votes
0answers
143 views

Compile not correctly initializing a variable defined inside Module

In the following example, inside the minimumX's Module, x is initialized to 1, but the ...
8
votes
3answers
165 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
2answers
126 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
2answers
146 views

Possible to scope an anonymous function within Module?

This is my first question. I'm fairly new to Mathematica and completely new to SE, so I apologize if this question is trivial. I'm working on a problem that requires a function to be redefined ...
8
votes
1answer
105 views

Does the syntax coloring I see indicate a real problem?

I need a behaviour provided by: x = 2; Block[{x = HoldForm[x]}, x] x FrontEnd marks ...
8
votes
1answer
120 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 ...
8
votes
1answer
135 views

Is it possible to write a function immune to symbol redefinitions in any Block surrounding its invocation?

Normally, semantics of symbols used in a function definition can be changed by their redefinitions in Blocks surrounding the function invocation: ...
7
votes
4answers
383 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 have: ...
7
votes
3answers
250 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. ...
7
votes
1answer
181 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 ...
7
votes
2answers
149 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 ...
7
votes
1answer
212 views

Variable scoping in Module

I don't understand why $a$ and $b$ are not local in the following code: ...
7
votes
3answers
467 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 ...
7
votes
1answer
169 views

FullDefinition and Module local variable

I have a question about FullDefinition and how it interacts with the local variables of Module. I've created a few functions ...
7
votes
0answers
240 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 ...
6
votes
6answers
579 views

How can you give a Module a context and have its local variables and Modules belong to that context?

What would be the best way to give a module its own context and have its local variables and Modules belong to that context?
6
votes
4answers
455 views

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 ...
6
votes
1answer
236 views

Module variable scoping in Scheduled Tasks?

I ran across a scoping puzzle while experimenting with ScheduledTasks, and I'd be grateful for an explanation from the sages here. I found a workaround by intuitive horse sense, but was unable to ...
6
votes
1answer
59 views

How to reset the $ModuleNumber?

According to the documentation, we can reset $ModuleNumber to a positive machine integer. There is even an example in the doc: ...
6
votes
2answers
196 views

Variable scoping problem when mapping over delayed replacement

This is something that got me curious while I was playing around with Mathematica. Consider the following (contrived) example: ...
6
votes
1answer
185 views

Difficulty catching thrown errors in asynchronous tasks

In this Question, Leonid explained that module variables can get garbage collected from a chain of asynchronous tasks unless their Temporary attribute is cleared ...
6
votes
1answer
113 views

Strange behaviour of Internal`InheritedBlock

I was going to post an answer for fast way to replace all zeros in the matrix. I was even quite happy because timings were the same order of magnitude as others. The idea was to overwrite ...
6
votes
1answer
126 views

Creating a Block from a list of rules

How can I create a function which works like Block but takes a list of rules as its first argument, rather than a list of assignments? The function needs to be ...
5
votes
3answers
263 views

Notation for specifying transformation rules

I would like to have a compact notation for specifying conditions and results in transformation rules. Consider ReplaceAll: ...
5
votes
1answer
1k views

Module with “local functions”

I am trying to use a Module having "local functions", i.e., those which I need to define only inside this module. So I tried this: ...
5
votes
3answers
140 views

Prevent iterator name from being confused with symbol passed into function body

I have a massive amount of code with lots of Table and Sum inside a Module. Each with their ...
5
votes
1answer
227 views

Parts of Module body evaluated in external scope?

I have an expression that suggests that some expressions in a module body are dragging in definitions from outside the scope in a surprising way. First, consider a symbolic constant, ...
5
votes
2answers
123 views

Generating EventHandler using Table

I would like to change the edge color of a graph when double clicking on it, the following code works: ...
5
votes
2answers
115 views

Checkbox behaving weird when variables are local

I have a DynamicModule in which I need a checkbox with a Max in the dynamic part: ...