Following a tip in this post, I use string parameters to label my functions. For example, instead of f[x]:=x^2
, I use f["label",x_]:=x^2
.
Unfortunately, this strategy breaks the default values for optional arguments, at least when the default value is a global variable.
What should happen:
f[x_,y_:var]:=x+y
var=10;
f[1]
11
var=20;
f[1]
21
What happens when using string parameters as a label:
g["label",x_,y_:var]:=x+y
var=10;
g["label",1]
11
var=20;
g["label",1]
11
It doesn't update to the new value when the global variable is changed. Why not? And more importantly, how can I fix this (without changing my nice labeling scheme, I hope)?
var
andg
as you're doing it, it will be obvious why the example shown exhibits the behavior you observe, and why that behavior is expected and unrelated to your "label" construct. $\endgroup$ClearAll[var]; g["label",x_,y_:var]:=x+y;
. (I'd recommendClearAll[g, var]
.) $\endgroup$ClearAll
or to re-define every function. $\endgroup$ClearAll
-- you're stuck with how Mathematica works. But here's an alternative:Block[{var}, g["label", x_, y_: var] := x + y ]
$\endgroup$ClearAll
between every time I decide to change the value ofvar
. In fact, I just need to use it once to clearvar
, then re-define the function so thatvar
remains in the function definition, and then the function responds to changes invar
. $\endgroup$