4
$\begingroup$

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.

$\endgroup$

2 Answers 2

7
$\begingroup$

How about this?

m[x_Symbol[___] /; Context[x] === "X`"] := True 
$\endgroup$
0
$\begingroup$

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.

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.