# Pattern match any member of a Context

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

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


and the reverse is also straightforward

g[_Xx] := True; g[_] := False
{ g[x[]], g[Xx[]] }
(* {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[Xx[]], h[Xy[]] }
(* {False, True, True} *)


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

-

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[Xx[]], m[Xy[]] }
(* {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.

-
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[Xx[]] 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