Re: named pattern variable scoped as global, should be local
- To: mathgroup at smc.vnet.net
- Subject: [mg56743] Re: [mg56696] named pattern variable scoped as global, should be local
- From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
- Date: Thu, 5 May 2005 06:01:25 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
>-----Original Message----- >From: leenewman at gmail.com [mailto:leenewman at gmail.com] To: mathgroup at smc.vnet.net >Sent: Wednesday, May 04, 2005 6:33 AM >Subject: [mg56743] [mg56696] named pattern variable scoped as global, >should be local > >When using a named pattern variable within a module, it should be >scoped locally within the pattern. However, this does not seem to work >as advertised. For example, shouldn't the pattern variable x in the >statements below be local to the pattern? Does anyone know whether >this is a bug, or whether I am just missing something about the usage >of variables in patterns/condition constructs? > >(* this returns 14! *) >x = 7; >Module[{x},{1, 2, 3} /. x_ -> 2x]; > >(* this returns {2,4,6}, assuming q is not globally defined. *) >Remove[q]; >Module[{q},{1, 2, 3} /. q_ -> 2q]; > > >Lee > > Lee, Help tells you that Rule is a Scoping Construct, such the pattern variable x (or q) in your examples never is the localized variable from Module. Such simply dispose with Module (for this). It is just the same as In[17]:= {1, 2, 3} /. x_ -> 2x Out[17]= 14 Now why 14? This is a consequence of In[18]:= Attributes[Rule] Out[18]= {Protected, SequenceHold} i.e. the right hand side is evaluated before the pattern valiable gets a value, such the global x is taken for that. This is done deliberately and intended. If you want to avoid that, use RuleDelayed: In[19]:= {1, 2, 3} /. x_ :> 2x Out[19]= {2, 4, 6} This behaviour is fully consistent with (and analogous to) the semantics of Set and SetDelayed. In the rare case you want to have the rhs of Rule evaluated before assigning the pattern variable, but retain the meaning as the pattern variable use Block: In[20]:= Block[{x}, {1, 2, 3} /. x_ -> 2x] Out[20]= {2, 4, 6} Of course if the global varable is not existent or has no value, then the pattern variable is used in any case: In[21]:= x =.; {1, 2, 3} /. x_ -> 2x Out[22]= {2, 4, 6} -- Hartmut Wolf