Skip to main content

programming - Localizing Pattern Names


When I want to define a function that uses a pattern, how should I localize the pattern name (i.e., x_ localizing the symbol x)? I have traditionally used Module but Workbench seems to freak out at times that I have unused symbols. Is this just a bug in Workbench, or is there a proper way of doing this?


Edit



So I have been a bit vague in exactly what I mean. To clarify, suppose I make a function in Workbench as:


test[g_, f_] :=
Module[{x},
g /. f[x_] :> x
]
]

I will have an error on the Module line stating "the local variable 'x', is not used". Please note this example is just to give the bare minimum so that I get the Workbench error, and to illustrate what kind of localization I mean. That is I want to use a symbol for use in a pattern label, not as a variable.



Answer



Considering your update, I'd like to point out that RuleDelayed or :> also localizes its symbols, so there is no need to use Module or any other construct to force localize them. For example:



x = 1;
{1, 2, 3} /. x_?EvenQ :> "foo"

(* {1, "foo", 3} *)

Also, the documentation for RuleDelayed says this:



Module and With do not affect local variables of RuleDelayed:


 With[{x = 1}, a /. x_ :> x + 1]
(* 1 + a *)


Taking that example a bit further, you can see from the following that inside the scope of RuleDelayed, the definition of x in Module is disregarded (it really is x$foo), but outside its scope, the definition in Module kicks in:


Module[{x = b}, (a /. x_ :> x + 1) x]
(* (1 + a) b *)

Comments