5
$\begingroup$

I defined a function TestHead in a notebook as follows:

TestHead[z___] := TrueQ[{z} == Cases[{z}, x_ /; Head[x] === avar]] 

to test whether a bunch of variables all have a certain head avar. When I do this in a notebook and define a variable a using

a /: Head[a]=avar 

this works fine and gives True for TestHead[a]. However, when I make a package

BeginPackage["TestHead`"] TestHead::usage="" Begin["`Private`"] TestHead[z___] := TrueQ[{z}==Cases[{z},x_/;Head[x]===avar]] End[] EndPackage[] 

load the package and again define a variable a as above, the function TestHead now gives False when acting on a.

Why is this and how I can remedy it?

$\endgroup$

2 Answers 2

3
$\begingroup$

It's because avar is in the TestHead`Private` context. One fix is to write your package with an explicit context on avar, such as Global`:

TestHead[z___] := TrueQ[{z}==Cases[{z},x_/;Head[x]===Global`avar]] 

You could have debugged this for instance with Trace and you would have seen instantly, why your SameQ results in False:

Trace@TestHead[a] (* {TestHead[a],TrueQ[{a}==Cases[{a},TestHead`Private`x_/;Head[TestHead`Private`x] ===TestHead`Private`avar]], {{Cases[{a},TestHead`Private`x_/;Head[TestHead`Private`x]=== TestHead`Private`avar],{{Head[a],avar},avar===TestHead`Private`avar,False},{}}, {a}=={},False},TrueQ[False],False} *) 
$\endgroup$
3
$\begingroup$

The other possibility, of course, is to have avar be declared by the package (it will thus be under the TestHead` context, i.e. its full declaration is TestHead`avar):

BeginPackage["TestHead`"] TestHead::usage = "" avar::usage = "" Begin["`Private`"] TestHead[z___] := TrueQ[{z} == Cases[{z}, x_ /; Head[x] === avar]] End[] EndPackage[] 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.