1

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

WillG
  • 960
  • 4
  • 14
  • 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. – ciao Mar 08 '20 at 00:21
  • Try ClearAll[var]; g["label",x_,y_:var]:=x+y;. (I'd recommend ClearAll[g, var].) – Michael E2 Mar 08 '20 at 00:26
  • 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. – WillG Mar 08 '20 at 00:27
  • @MichaelE2 Maybe it does, but I don't understand it. I'm not sure how HoldFirst etc. enter into my situation. – WillG Mar 08 '20 at 00:29
  • The relevant point is that var is evaluated when the Optional default is set in the definition of g. If var has a value when g is defined, then that value becomes the permanent default. If it does not, then var "evaluates" to the expression var which is used as the default. You must have defined g when var = 10. Execute ?g to see the definition of g; you should see g["label", x_, y_ : 10] := x + y. Then clear var and redefine g. Then ?g should show g["label", x_, y_ : var] := x + y. – Michael E2 Mar 08 '20 at 00:40
  • 1
    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 ] – Michael E2 Mar 08 '20 at 00:46
  • 1
    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. – WillG Mar 08 '20 at 00:50
  • Right! :) -- Best, – Michael E2 Mar 08 '20 at 01:51
  • Related: https://stackoverflow.com/q/6337753 – Mr.Wizard Mar 08 '20 at 03:35

0 Answers0