Re: Scoping and named patterns
- To: mathgroup at smc.vnet.net
- Subject: [mg18173] Re: Scoping and named patterns
- From: Dr Dan <drdanw at my-deja.com>
- Date: Sat, 19 Jun 1999 23:54:32 -0400
- Organization: Deja.com - Share what you know. Learn what you don't.
- References: <7kcjrn$lql@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
In article <7kcjrn$lql at smc.vnet.net>,
Dr Dan <drdanw at my-deja.com> wrote:
> I am having trouble with name conflicts between global symbols and
> named patterns.
>
> This example from The Book works fine:
>
> In[1]:= f[a^b] /. f[x : _^n_] -> p[x, n]
> Out[1]= p[a^b, b]
>
> But if the symbols used as pattern names have values:
>
> In[3]:= n = 2; x = 3;
> f[a^b] /. f[x : _^n_] -> p[x, n]
> Out[3]= p[3, 2]
>
> My usual favorite scoping structure, Module, doesn't help:
>
> In[4]:= Module[{x, n}, f[a^b] /. f[x : _^n_] -> p[x, n]]
> Out[4]= p[3, 2]
>
> This shows that the global symbol is used as the pattern name and not
> the symbol local to the scoping construct:
>
> In[5]:= Module[{x, n}, Clear[x, n]; f[a^b] /. f[x : _^n_] -> p[x, n]]
> Out[5]= p[3, 2]
>
> Since local symbols are ignored, it is necessary to use Block:
>
> In[6]:= Block[{x, n}, f[a^b] /. f[x : _^n_] -> p[x, n]]
> Out[6]= p[a^b, b]
>
> This looks like a bug to me. If I use a symbol in a local context I
> expect the local symbol and never the global. I am a little concerned
> that the pattern itself doesn't scope its pattern names, that I can
> make one seemingly small change in my notebook and my patterned
> replacements begin crashing.
>
> Any comments, or a better workaround than Block?
Just after posting the above message, I discovered that the Block
solution doesn't always work. My original intent was to store a
complicated rule for use elsewhere in the notebook:
In[1]:= n = 2; x = 3;
In[2]:= r = Block[{x, n}, f[x : _^n_] -> p[x, n]];
f[a^b] /. r
Out[3]= p[3, 2]
Oops. Now my replacement is outside the block. Then I stumbled upon
the correct solution (without knowing why it worked), using RuleDelayed:
In[4]:= r = f[x : _^n_] :> p[x, n];
f[a^b] /. r
Out[5]= p[a^b, b]
This seems to be a robust solution. Read the other postings in this
thread for a much better explanation than I can give. Thank you for
the help.
Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
- Follow-Ups:
- Re: Re: Scoping and named patterns
- From: "Wolf, Hartmut" <hwolf@debis.com>
- Re: Re: Scoping and named patterns