2
$\begingroup$

I have:

BeginPackage["Test1`"];
ClearAll[f];
f::usage = "";
Begin["`Private`"];
f[x_AA]:= 1;
f[x_BB]:= 2; 
End[];
EndPackage[];

When later, on a notebook, after the call package successful with:

<<Test1`

I always get from evaluated:

x = AA[3];
f[x]

It should be: 1. But, actually, It is f[AA[3]]. The issue is same if I used x = BB[4];

Any idea? I don't realize how to make it works.

$\endgroup$
  • $\begingroup$ That Print[1] prints 1 is actually not its result, it's a side-effect. Just try Print[1] // FullForm and you get Null. $\endgroup$ – Sjoerd C. de Vries May 21 '15 at 19:56
  • 1
    $\begingroup$ This question can be found here, the answer useful: mathematica.stackexchange.com/q/7502/7251 $\endgroup$ – jonaprieto May 21 '15 at 21:12
  • $\begingroup$ Possible duplicate: (15870) $\endgroup$ – Mr.Wizard May 22 '15 at 13:13
5
$\begingroup$

AA and BB in the definition of f are local symbols of the Test1`context. If you want to use them in the Global context you have to export them from the package or you have to precede them with their context:

f[Test1`Private`AA[3]]

1

Or

BeginPackage["Test1`"];
ClearAll[f];
f::usage = "";
AA::usage = "";
BB::usage = "";
Begin["`Private`"];
f[x_AA] := 1;
f[x_BB] := 2;
End[];
EndPackage[];

f[AA[3]]

1

$\endgroup$
  • $\begingroup$ Oh, sure. it is a solution. Thanks. $\endgroup$ – jonaprieto May 21 '15 at 20:18
  • 2
    $\begingroup$ It actually suffices to include the line AA; BB; just before the Begin[] if you don't want to bother with writing usage messages for them. $\endgroup$ – J. M. will be back soon May 21 '15 at 20:22
  • $\begingroup$ I'm just repeating the OP's original pattern, assuming he left the usage string empty to reduce the size of the example. $\endgroup$ – Sjoerd C. de Vries May 22 '15 at 6:04

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.