Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers 2

up vote 2 down vote accepted

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}
*)
share|improve this answer
add comment

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[]
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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