MathGroup Archive 1998

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Previous variable affects "/."


  • To: mathgroup@smc.vnet.net
  • Subject: [mg11276] Re: Previous variable affects "/."
  • From: sb.nospam@stonesoft.com (Stonewall Ballard)
  • Date: Wed, 4 Mar 1998 01:39:30 -0500
  • Organization: StoneSoft, Inc.
  • References: <6dg8bd$2tr@smc.vnet.net>

In article <6dg8bd$2tr@smc.vnet.net>, Vilis Nams <vnams@nsac.ns.ca>
wrote:

> I am using "/." to change expressions, as follows:
> 
> In[1]:= a = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; In[2]:= a /. {x_,
> y_} -> {x}
> Out[2]:= {{1}, {3}, {5}, {7}}
> The results are expected.
> 
> But, if I now define x to be something already, e.g. In[3]:= x = 7;
> 
> Then, when I do the Replace, Mathematica uses my previously-defined x,
as follows=
> :
> 
> In[4]:= a /. {x_, y_} -> {x}
> Out[4]:= {{7}, {7}, {7}, {7}}
> 
> I tried to even wrap it inside of a function, to have x as a local
> variab= le, as
> in:
> In[5]:= f[v_] := Module[{x, y}, v /. {x_, y_} -> {x}];
> 
> But, it still used the x defined previously: In[6]:= f[a]
> Out[6]:= {{7}, {7}, {7}, {7}}
> 
> This is no problem when I'm just creating and using variables in one
> se= ssion,
> because I can remember which variables I created. But, I have such
> Replac= e
> statements sprinkled inside of functions that I defined. I cannot
> remembe= r all
> the symbols I used in those definitions. Even worse, I may not get an
> err= or
> message - I just may get the wrong result without knowing it.
> 
> How can I use the Replace and x_, and make sure that previously-defined
> variables don't influence the results?

Since I'm still learning the Mathematica language, this looked like a
good test.

The short answer is that it works if you use :> instead of ->. You don't
need the Module.

Neither Rule (->) nor ReplaceAll (/.) have Hold args, so the fact that
there's an x in the pattern is irrelevant. The RHS x will be
transformed into its global value before Rule runs.

I think the reason that Module fails is that it substitutes "for each of
the local variables that appear anywhere in expr except as local
variables in scoping constructs". Rule says "Rule is a scoping
construct". It's strange to have a scoping construct without Hold args
- that's where the confusion arises.

Note that Block works.

  - Stoney

-- 
Stonewall Ballard                    StoneSoft, Inc.
sb.nospam@stonesoft.com    http://www.stonesoft.com/



  • Prev by Date: Re: Mathlink what is P(( ))
  • Next by Date: RE: algebraic solutions
  • Prev by thread: Re: Previous variable affects "/."
  • Next by thread: Re: Previous variable affects "/."