4

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.

rcollyer
  • 33,976
  • 7
  • 92
  • 191

2 Answers2

7

How about this?

m[x_Symbol[___] /; Context[x] === "X`"] := True
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
0

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.

rcollyer
  • 33,976
  • 7
  • 92
  • 191
  • 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
  • @Mr.Wizard As to what I wish to accomplish, I wish to match an expression that has a Head that is a member of a specific context. To have a head, it must be a function, such as List. That is why my examples are littered with x[], not x. In the case of _?(Context @@ # == "X`" &), x[] is passed to PatternTest, not x as Context expects. So, I have to strip off everything but the Head. – rcollyer Jan 21 '13 at 16:07