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.


2 Answers 2


How about this?

m[x_Symbol[___] /; Context[x] === "X`"] := True

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.

  • $\begingroup$ Wait a minute, why can't you use _?(Context @@ # == "X`" &) ? $\endgroup$
    – Mr.Wizard
    Commented Jan 21, 2013 at 15:41
  • $\begingroup$ @Mr.Wizard Context expects a symbol or string, so Context[X`x[]] generates an error. $\endgroup$
    – rcollyer
    Commented Jan 21, 2013 at 15:44
  • $\begingroup$ Why would it see that in your example? How else are you using this pattern? $\endgroup$
    – Mr.Wizard
    Commented Jan 21, 2013 at 15:45
  • $\begingroup$ 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? $\endgroup$
    – Mr.Wizard
    Commented Jan 21, 2013 at 15:50
  • $\begingroup$ @Mr.Wizard that would work just as well, and I figured the answers would be straight forward. $\endgroup$
    – rcollyer
    Commented Jan 21, 2013 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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