Hot answers tagged

214

You will find a lot of information in this answer. I will add a few personal notes. Module Use Module when you want to localize variables inside your function's body, and those variables will potentially acquire and/or change their values during the computation. Basic use For example: f[x_]:=Module[{y=x^2},y=y+x;{x,y}] Here, a local mutable variable (...


83

The differences between Module, Block and With are nicely summarized by the results of the following expressions: x = "global"; f[] := x Module[{x = "local"}, {x, f[], Hold[x]}] Block[{x = "local"}, {x, f[], Hold[x]}] With[{x = "local"}, {x, f[], Hold[x]}] which returns: {"local", "global", Hold[x$123]} (* Module *) {"local", "local", Hold[x]} ...


64

I don't think one can avoid the need for nested With altogether - I find it a very common case to need declared variables use previously declared variables. Since I once wrote the function (actually macro) that automates nesting With, and generates nested With at run-time, this is a good opportunity to (re)post it as an answer to an exact question that it ...


55

Internal`InheritedBlock (IIB) is similar to Block, except that it preserves the original definition of the function being passed to it. The function can then be modified as we wish inside the IIB without affecting the external definition. Let's see how Block works first: f[x_] := x Block[{f}, Print@DownValues[f]; f[x_, y_] := x y; Print@...


53

Scoping constructs, lexical scoping and variable renamings It pays off to understand a bit deeper how the scoping constructs work and what happens behind the scenes when you execute one. In addition to the documentation, this was discussed in part here, but let us present some summary. When the lexical scoping construct Sc[vars, body] executes (where Sc ...


46

You are correct about the behavior of computations done from preemptive links. So-called "preemptive evaluations" have been around since version 6. They are a class of evaluations that all work through the same mechanism. When Mathematica checks to see if a user interrupt has been requested, which it does at a high rate most of the time, it also looks to see ...


45

Introduced in V10.4 or earlier, but after V10.1 This functionality has snuck into With (ref: Daniel's comment). Note the use of the braces. With[{v1 = #}, {v2 = f[v1]}, g[v1, v2]] (* g[#1, f[#1]] *) The syntax coloring has not caught up yet: In V10 -- Needs["GeneralUtilities`"]; ?GeneralUtilities`Where Where[ass1, ass2, ..., expr] is a version of ...


45

Safety Module is safer than Block because: It is a lexical scoping construct, which means that variable bindings are only tied to a specific piece of code. Variables outside that piece of code are never affected by these bindings. In contrast, Block basically binds a variable to a piece of execution stack, not a piece of code. Such bindings are much ...


40

I'll cover a few typical uses of Block, neither of which is possible using Module or With. Temporarily removing definitions When you do Block[ {a = x}, ... ] the original definition of a is effectively replaced by whatever new definition is given in the first argument of Block, for the duration of the evaluation of Block only. If we give no definition, ...


37

Symbols are created in the current context during parsing. This should not be a problem in normal circumstances as the symbols are merely "initialized" without values or properties. See these posts for more information: Is it possible to use Begin and End inside a Manipulate? Why doesn't this use of Begin[] work? When does Mathematica create a new Symbol? ...


35

Internal`LocalizedBlock behaves the same as Block, but it can localize non-Symbols (e.g. f[1], Subscript[x, 0], etc.). For example, Internal`LocalizedBlock[{Subscript[x, 0]}, Subscript[x, 0] = 1] (* 1 *) Compare this to Block[{Subscript[x, 0]}, Subscript[x, 0] = 1] (* During evaluation of In[79]:= Block::lvsym: Local variable specification {Subscript[x, ...


33

You cannot make definitions with patterns on the left-hand side in the first argument of a scoping construct (such as Module). You need do that in the body of the Module. You should also use a different symbol for the internal function parameter. norm[x_] := Module[{fun1, fun2}, fun1[p_] := p^2 + p - 1; fun2[p_] := p^3 - p^2 + p + 1; Max[...


32

Short answer The local variables of the form varname$... are used by the system, and it is unwise to use symbols with such names as local variables. With, like many other lexical scoping constructs, performs excessive renamings, often even in cases where it isn't strictly necessary. This probably has to do with efficiency - full analysis may be more costly. ...


28

With works by performing a substitution operation prior to executing its body, and likely it is only a single pass. So, inter-referencing the variables is not possible. Since With accepts the use of SetDelayed (:=), you might think that that could be used, instead. For example, With[{v1 = #, v2 := f[v1]}, g[v1, v2]]& @ p (* g[p, f[v1]] *) which reveals ...


27

Preliminaries As Todd has indicated in his answer which has a lot of excellent information, the situation where the described behaviour will actually trigger problems will be very rare. I also read from his answer that WRI doesn't consider this behavior to be a bug and my hopes that this might change in future versions are low or nonexistent. I show ...


27

The short answer is "yes", we should always use Module to localize any intermediate variables within our functions. We might get away with using global variables for everything in an ad hoc, interactive session. But as we accumulate function definitions that we wish to re-use repeatedly over time, the chances of this practice causing problems increases ...


26

Here is the almost obligatory timing response, it probably doesn't generalise very broadly but perhaps is indicative in some respects: (* no variables *) f1[x_] := (x^2; x^3;) f2[x_] := Module[{}, x^2; x^3;] f3[x_] := Block[{}, x^2; x^3;] f4[x_] := With[{}, x^2; x^3;] (* With variable definition *) f2[x_] := Module[{y = 0}, x^2; x^3;] f3[x_] := Block[{y = ...


25

There will no doubt be plenty of answers for this one. However the short answer is: Use With for local constants that you don't have to change subsequently. Use Module for local variables that are local to that piece of code. Use Block for local variables that are local to that sequence of evaluation. This tutorial in the Mathematica documentation ...


23

Usual caveats about using undocumented functions aside, here is how one might use Internal`WithLocalSettings[]: With[{plotOptions = Options[Plot]}, Internal`WithLocalSettings[SetOptions[Plot, PlotStyle -> Green], Plot[Sin[x], {x, -π, π}], SetOptions[Plot, plotOptions]]] but I do not ...


22

I will leave the explanation of the difference between lexical and dynamic to those more qualified than myself (and to the documentation). One practical difference between Block and Module is this: Module[{x}, x] Block[{x}, x] (* -> x$1979 x *) That is, if you construct something inside a Block with a blocked variable and then return it, you may use ...


22

What's happening This is not simple by any means. You have encountered another instance of a general situation with lexical scope leaks / emulation / over-protection by symbol renaming. The case at hand is pretty similar to the one discussed here, so you can read the detailed explanation of this behavior in my answer there. Roughly speaking, outer lexical ...


21

For a single code statement, this is probably an overkill. If you have two or more of them, you have to group them in any case. CompoundExpression is one obvious choice, such as f[x_]:= ( Print[x]; x^2 ) Instead, you could also do f[x_]:= Module[{}, Print[x]; x^2 ] which is what I personally often prefer. Apart from some stylistic ...


21

Preamble What happens can be understood when we recall that Rule is a scoping construct. The general issues related to variable renamings in scoping constructs have been considered in more details in this answer. General Now, to this particular case. When the code runs, the external RuleDelayed considers the situation "dangerous" and performs variable ...


21

Based on Mr.Wizard's answer and comments by Szabolcs and celtschk, I now understand that the code I posted does have undesirable side-effects and it should be avoided. Specifically, the scoping constructs Module and Block are meant to completely localize the variables in their first argument (for more information see this question). However, placing their ...


21

A long comment: Automatic renaming again: ClearAll[F]; F[x_] := Hold[With[{a = x}, {b = x}, a]]; F[0] Hold[With[{a$ = 0}, {b = 0}, a]] I was expecting it already in DownValues, but this is not the case. DownValues @ F {HoldPattern[F[x_]] :> Hold[With[{a = x}, {b = x}, a]]} So who does it? :) Here is a pure guess, if evaluation is really a ...


20

Try for example SetAttributes[def, HoldAll] def[s_Symbol, v_] := Function[Null, s[x_] := #, HoldFirst][v] Unnamed functions just don't care :) Other alternatives that should also work (but I would use the previous approach) def[s_Symbol, v_] := Identity[SetDelayed][HoldPattern@s[x_], v]; def[s_Symbol, v_] := Unevaluated[s[x_] := "Hello"] /. "Hello" -> ...


20

What happens and why As Daniel Lichtblau pointed out in comments, this behavior can also be viewed as a flaw in the current behavior / design / implementation of lexical scoping in Mathematica. However, it may be useful still to understand on a deeper level what happens, since it can be explained rather easily from the core rules of how lexical scoping ...


20

In general, it is good practice to include i among the local variables. Table does not localize its variable (or, as some say, it only localizes the value but not the variable). It is relatively safe to leave i unlocalized when variables only have numeric values, like in fun. But the same is not true when variables can have symbolic values, e.g.: fun2[x_]...


20

Why is this happening The explanation was basically given by ciao in comments. You can also find a lot of information on this in this great answer of Mr.Wizard. I will perhaps try to view it from a somewhat different perspective. To understand what happens, one should go back and consider what happens when we enter and execute some code. The steps are ...


Only top voted, non community-wiki answers of a minimum length are eligible