I have defined a function g
in a package. It is:
g[x_]:=x/.t->3
Now I work in notebook with the command:
a=t+1;
g[a]
The result is not 4
but 1+t
. What can I do to get the result of 4
?
The package file "pack1.m" is like this:
BeginPackage["pack1`"]
g::usage =""
Begin["`Private`"]
g[x_]:=x/.t->3
End[ ]
EndPackage[ ]
And I use <
Answer
For the specific example you provided, you can replace t
with Global`t
and it should work.
However, it is generally not a good idea to access/share/set Global`
variables with a package. While it is OK for small cases like this, if you make this a habit, you'll run into troubles with larger packages, where it becomes harder to debug or if you share this package with someone else who doesn't know what transpires under the hood, or if you/they have accidentally set a value for t
, etc.
Instead, I suggest using a slightly more verbose definition for g
as (ignore the red coloring):
SetAttributes[g, HoldAll]
g[expr_, rule_, var_] := Block[{var}, expr /. rule]
which allows you more flexibility. You can now do g[t+1, t -> 3, t]
to get 4, and it doesn't matter if you've already set a value for t
in your current session. If you decide later to change the rule, you needn't edit your package... you simply need to change the second argument to g
! You can tweak the above around to your specific needs, and perhaps infer the variable t
automatically from rule
, etc., but the idea remains the same.
Comments
Post a Comment