1
$\begingroup$

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)?

$\endgroup$
9
  • $\begingroup$ It behaves exactly the same way, with or without your "label" construct. Hint: Look carefully at what you're doing and the state of var and g 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$
    – ciao
    Commented Mar 8, 2020 at 0:21
  • $\begingroup$ Try ClearAll[var]; g["label",x_,y_:var]:=x+y;. (I'd recommend ClearAll[g, var].) $\endgroup$
    – Michael E2
    Commented Mar 8, 2020 at 0:26
  • $\begingroup$ But I want to be able to change my global variable frequently and have the functions respect the change, without having to use ClearAll or to re-define every function. $\endgroup$
    – WillG
    Commented Mar 8, 2020 at 0:27
  • 1
    $\begingroup$ I don't understand the objection to ClearAll -- you're stuck with how Mathematica works. But here's an alternative: Block[{var}, g["label", x_, y_: var] := x + y ] $\endgroup$
    – Michael E2
    Commented Mar 8, 2020 at 0:46
  • 1
    $\begingroup$ Ohhh. Now I see. I thought you were suggesting to use ClearAll between every time I decide to change the value of var. In fact, I just need to use it once to clear var, then re-define the function so that var remains in the function definition, and then the function responds to changes in var. $\endgroup$
    – WillG
    Commented Mar 8, 2020 at 0:50

0