This seems like an obvious issue that I have nevertheless never encountered before.
In a package, I want to use a variable to define a pattern that is used in the definition of some functions. However the actual pattern is not defined until run-time. Unfortunately MMA refuses to use the updated values in the variable, and the function definitions retain the original symbol definition that was set within the package. The function 'Update
' is of no assistance:
ClearAll[testF,$symbols]
$symbols="placeholder";
testF[$symbols]:="It works!!!"
testF[___]:="Failed!!!"
(*Sometime later, after the package has been loaded, a new definition of $symbols is made:*)
$symbols=Alternatives@@{a,b,c};
(* However it is clear that the updated $symbols is not being used, the "placeholder"
value having been inserted, and $symbol not appearing at all within the DownValues:*)
DownValues[testF]
(*-> {HoldPattern[testF["placeholder"]]:>"It works!!!", HoldPattern[testF[_]]:>"NO!!!"} *)
(*And of course it is impossible for testF[a] to work as expected:*)
testF[a]
(*-> "NO!!!" *)
(* 'Update' is useless: *)
Update[testF]
Update[$symbols]
(* -> syntax errors for Update[$symbols] because the Alternatives are inserted.*)
(* Downvalues of 'testF' are unchanged, and the function still fails: *)
testF[a]
(*-> "NO!!!" *)
Of course all works fine if the first $symbols
definition ($symbols="placeholder";
) is just replaced with the second, but that just defeats the purpose. I want the testF
definition to inherit the changes to $symbols
.
Q: How to get $symbols
to be retained in its symbolic form within the testF DownValues so that when I update from 'placeholder' to the Alternatives ($symbols=Alternatives@@{a,b,c};
) then testF
reflects the changes?
$symbols
. When you evaluatedtestF[$symbols] := "It works!!!"
,$symbols
was evaluated to be "placeholder" and therefore testF is defined in terms of "placeholder". You haven't specified what behavior you want. So, specifically, after$symbols=Alternatives@@{a,b,c}
what do you want testF to return then? I suspect that you want to use$symbols
on the right-hand side of your definition of testF, but you need to explain to us the behavior you want. $\endgroup$$symbols
, then write it that way. Somethinng liketestF[] := Switch[Head[$symbols], String, "it works with string", Alternatives, "it works with alternatives", _, "i don't handle that form"]
$\endgroup$testF[a]
returns "It works!". The problem is that the definition viz$symbols
is inserted immediately whentestF
is defined. There is no way to force it to be retained in symbolic form except by putting it inside of aCondition
statement. $\endgroup$