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

learn more… | top users | synonyms (1)

104
votes
7answers
4k 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: ...
23
votes
4answers
539 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 ...
36
votes
4answers
867 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 ...
10
votes
2answers
620 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 ...
7
votes
4answers
448 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 ...
2
votes
1answer
266 views

Call Functions From File Without Modifying Context (Sandbox)

Let's say I have file named test.m containing test[arg1_] := ( Print[arg1];) What is the best technique for calling test like ...
35
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 ...
13
votes
3answers
380 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 ...
13
votes
1answer
306 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: ...
7
votes
0answers
271 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 ...
7
votes
4answers
564 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 ...
7
votes
3answers
330 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
252 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 ...
7
votes
6answers
594 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?
9
votes
3answers
298 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 ...
3
votes
2answers
267 views

Why does the syntax highlighter color a local symbol red inside DynamicModule?

I am adding a Module inside DynamicModule here is an example (thanks to @rm-rf for this simple example) ...
24
votes
1answer
245 views

What does Internal`InheritedBlock do?

What does the function Internal`InheritedBlock do? How is it different from the regular Block?
15
votes
2answers
267 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 ...
14
votes
1answer
315 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 ...
13
votes
1answer
293 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
324 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 ...
6
votes
1answer
142 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 ...
9
votes
1answer
131 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 ...
4
votes
3answers
142 views

Altering values in Manipulate with dynamically generated controls

I have a Manipulate whose controls are generated based on a parameter in a containing Manipulate: ...
3
votes
1answer
150 views

Issue with scope of variables

For the definitions, t = 1; f[x_, y_] := t (x + y); v[3] := {1, 1}; g[u_] := f[v[u][[1]], v[u][[2]]]; the following two expressions yield different results, ...
1
vote
1answer
70 views

NDSolve inside Module with local variables

I want to use NDSolve within a Module and output the solution at some times. (Mathematica 10) All works fine with global variables (symbols) ...
21
votes
2answers
939 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?). ...
10
votes
2answers
251 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 ...
5
votes
0answers
114 views

Are there any videos that show how different Mathematica expressions are evaluated?

Are there any videos that show how different Mathematica expressions are represented internally as object graphs and demonstrate how they are transformed during an evaluation? I am asking because I ...
18
votes
1answer
205 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, ...
7
votes
3answers
563 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 ...
9
votes
2answers
238 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
1answer
129 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: ...
7
votes
1answer
238 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 ...
6
votes
1answer
187 views

Treat all variables as local in a module [duplicate]

In most languages, any variable defined inside a function is considered local. ...
4
votes
0answers
150 views

Exhaustive examples of variable replacement due to nested scoping constructs

Consider the following examples, where I have replaced dollar signs in the output by a D. ...
4
votes
1answer
196 views

How to avoid conflicts between local variable names and symbolic arguments in Block constructs?

I am using Block inside the definition of some recursive functions. If the Block definitions use short variable names, like ...
11
votes
2answers
418 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. ...
11
votes
0answers
176 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
2answers
136 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 ...
6
votes
1answer
143 views

How to inherit options by scoping?

Consider the following example: you have a function framed producing a cell with a button that, when pushed, calls framed again. ...
5
votes
3answers
145 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 ...
4
votes
1answer
84 views

Module does not remove a function definition

The following is a minor variant of the function uniqueTuples as given by Simon Woods in this answer. ...
4
votes
2answers
272 views

Comparing LetL and Module efficiency

I was recently introduced to the LetL macro thanks to Leonid's answer to one of my prior questions. I was, needless to say, impressed by the simplicity of its ...
3
votes
1answer
72 views

Evaluating arguments of module (inside compile)

Note: this is a clarification of 2 earlier unanswered questions, Compile issues, scoping and order of evaluation and Optimising a simple computation with vectors . The problem I have a list of ...
3
votes
3answers
102 views

Name scope confusion

Sorry for the too ambiguous title. First consider a following code snippet. ...
3
votes
2answers
214 views

How to declare a function that uses local variables of a module outside this module?

I have the following code Module[{f,x=0}, f[t_] := x + t; ..........; ...f[1]...; ..........; ] My aim is to put the declaration of the function ...
3
votes
2answers
428 views

Local variables

I'm trying to use Modules together with functions. tmp2 = x^2 + 1; f[y_] := Module[{x = 1}, Evaluate[y tmp2]] This works when ...
2
votes
0answers
86 views

Compile issues, scoping and order of evaluation

I have a few questions about compiling functions, which I think are all related to scoping and order of evaluation. I will illustrate them by a minimal example of the problem I have. I'm sorry for ...
2
votes
1answer
46 views

Is the use of Block to temporarily override definitions inherently unsafe? [duplicate]

This may have been discussed before, if so, please let me know. Consider the following example: x = 5 Dynamic[{Clock[], x}] This will always display the ...