I'm trying to be sneaky with a function and try to have an expression stored as a string (unevaluated) until a desired moment when it will be converted from a string to an expression and then have it parsed.
I am doing this because some computations are quite heavy and depending on what I want from the function I can either get the "a" or "b" outputs/paths. I suspect that SetDelayed
or TagSetDelayed
would probably be better suited here, but I'm not certain how to use them in this context.
This works beautifully as a normal function (non-packaged) in a notebook (v.13.2) however the moment I introduce this idea in a package environment, it fails to parse it.
The packaged version:
BeginPackage["SE`Question`"];
func1; (* declared in public part of package *)
Begin["`Private`"];
func1[a_,b_,output_:"a"]:=Block[{range,data1,data2,dict,dat1,dat2},
range=Range[10];
data1 = Table[i^a,{i,10}];
data2 = Table[i^b,{i,10}];
dict=<|
"a"->"{range,data1}\[Transpose]",
"b"->"{range,data2}\[Transpose]"
|>;
ToExpression[Evaluate[dict[output]]]
]
End[];
EndPackage[];
The non-packaged version
Clear[func2]
func2[a_,b_,output_:"a"]:=Block[{range,data1,data2,dict},
range=Range[10];
data1 = Table[i^a,{i,10}];
data2=Table[i^b,{i,10}];
dict=<|
"a"->"{range,data1}\[Transpose]",
"b"->"{range,data2}\[Transpose]"
|>;
ToExpression[Evaluate[dict[output]]]
]
Output
func1[2,4,"a"] (* the packaged function *)
func2[2,4,"a"] (* the non-packaged function *)
If someone could please explain why this happens or better yet suggest an alternative I would be very grateful.
dict=<| "a"->out1, "b"->out2 |>; Evaluate[dict[output]]/.{out1:>{range,data1}\[Transpose],out2:>{range,data2}\[Transpose]}
usingRuleDelayed
does the trick. $\endgroup$