0
$\begingroup$

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 <<pack1.m to load it.

$\endgroup$
  • $\begingroup$ In which context have you defined your package functions? Have you made them "public"? Have you imported them to the current session? Are you sure you're using the same g? It should work if you've done it right. $\endgroup$ – rm -rf Jul 13 '13 at 17:33
  • $\begingroup$ I don't know how to make a variable "public". I want to share "t" between two context. I add "t=Global`t" in package and it is still wrong. $\endgroup$ – cmc Jul 13 '13 at 17:51
  • $\begingroup$ If you do g[x_] := x /. Global`t -> 3, it should work. $\endgroup$ – rm -rf Jul 13 '13 at 17:57
  • $\begingroup$ Now it work nice. Thank you. $\endgroup$ – cmc Jul 13 '13 at 18:01
  • $\begingroup$ Related question. $\endgroup$ – Leonid Shifrin Jul 14 '13 at 12:06
5
$\begingroup$

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.

|improve this answer|||||
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.