Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Let's say I have four functions: x, y, X`x, and X`y. Writing a pattern that matches x, but not X`x is easy

f[_x] := True; f[_] := False
{ f[x[]], f[X`x[]] }
(* {True, False} *)

and the reverse is also straightforward

g[_X`x] := True; g[_] := False
{ g[x[]], g[X`x[]] }
(* {False, True} *)

But, how would I match all members of X`?

Obviously, this works

h[_?(MemberQ[Names["X`*"], ToString@Head@#] &)] := True
h[_] := False
{ h[x[]], h[X`x[]], h[X`y[]] }
(* {False, True, True} *)

but it seems excessive, especially if the Context contains a large number of functions.

share|improve this question

How about this?

m[x_Symbol[___] /; Context[x] === "X`"] := True
share|improve this answer

This is not as simple as I would like, but it seems like it is less computationally complex than the Names method, above.

m[_?(Context @@ {Head@#} == "X`" &)] := True
m[_] := False
{ m[x[]], m[X`x[]], m[X`y[]] }
(* {False, True, True} *)

Unfortunately, Context has a HoldFirst attribute, so I used Apply (@@) to get around it. It could have just as easily been done using With.

share|improve this answer
Wait a minute, why can't you use _?(Context @@ # == "X`" &) ? – Mr.Wizard Jan 21 '13 at 15:41
@Mr.Wizard Context expects a symbol or string, so Context[X`x[]] generates an error. – rcollyer Jan 21 '13 at 15:44
Why would it see that in your example? How else are you using this pattern? – Mr.Wizard Jan 21 '13 at 15:45
I don't think I understand your requirements so I've lifted my vote for the time being. I cannot figure out what you're actually trying to match. It seems to me that something like a_Symbol[___] /; Context[a] === "X`" may be better. Would you please try to explain in more detail what you're doing? – Mr.Wizard Jan 21 '13 at 15:50
@Mr.Wizard that would work just as well, and I figured the answers would be straight forward. – rcollyer Jan 21 '13 at 16:04

Your Answer


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.