Bound local variables in Mathematica
Posted by David Zaslavsky on — CommentsWhen writing a computer program in a language that allows function definitions inside code blocks, it’s pretty common to create a function that references some variable in an enclosing scope. And sometimes you want to delete that variable without making it inaccessible to the function. In Mathematica, you can use Module
to do this:
a = 4;
f[x_] = Module[{b=a}, If[x>0,x+b,0]];
Since I used a regular assignment =
to define f[x_]
rather than delayed assignment :=
, this stores the value of a
in a “local” variable named something like b$120938
, so even after I run
Clear[a];
f[x]
still adds four to \(x\), so, for example, f[1]
would return 5.
In contrast, if I use Block
, Mathematica won’t store the value of a
.
a = 4;
f[x_] = Module[{b=a}, If[x>0,x+b,0]];
Clear[a];
After this code snippet f[1]
would just return 1+b
. (For some reason Mathematica doesn’t seem to recognize that b
has a value of a
inside the If
statement… I’m not sure if this is intentional behavior.)