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)?
varandgas 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. – ciao Mar 08 '20 at 00:21ClearAll[var]; g["label",x_,y_:var]:=x+y;. (I'd recommendClearAll[g, var].) – Michael E2 Mar 08 '20 at 00:26ClearAllor to re-define every function. – WillG Mar 08 '20 at 00:27HoldFirstetc. enter into my situation. – WillG Mar 08 '20 at 00:29varis evaluated when theOptionaldefault is set in the definition ofg. Ifvarhas a value whengis defined, then that value becomes the permanent default. If it does not, thenvar"evaluates" to the expressionvarwhich is used as the default. You must have definedgwhenvar = 10. Execute?gto see the definition ofg; you should seeg["label", x_, y_ : 10] := x + y. Then clearvarand redefineg. Then?gshould showg["label", x_, y_ : var] := x + y. – Michael E2 Mar 08 '20 at 00:40ClearAll-- you're stuck with how Mathematica works. But here's an alternative:Block[{var}, g["label", x_, y_: var] := x + y ]– Michael E2 Mar 08 '20 at 00:46ClearAllbetween 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 thatvarremains in the function definition, and then the function responds to changes invar. – WillG Mar 08 '20 at 00:50