MathGroup Archive 1998

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

Search the Archive

Re: Previous variable affects "/."



> I am using "/." to change expressions, as follows:
>
> In[1]:z {1, 2}, {3, 4}, {5, 6}, {7, 8}}; In[2]:z /. {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]: w;
>
> Then, when I do the Replace, Mathematica uses my previously-defined x, as follows
> :
>
> In[4]:z /. {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
> variabe, as
> in:
> In[5]:[v_] :odule[{x, y}, v /. {x_, y_} -> {x}];
>
> But, it still used the x defined previously: In[6]:[a]
> Out[6]:7}, {7}, {7}, {7}}
>
> This is no problem when I'm just creating and using variables in one
> session,
> because I can remember which variables I created. But, I have such
> Replace
> statements sprinkled inside of functions that I defined. I cannot
> remember all
> the symbols I used in those definitions. Even worse, I may not get an
> error
> 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?
>
>
> --------------------
> Vilis O. Nams
> Dept of Biology, NSAC
> Box 550, Truro, NS,  Canada
> vnams @ nsac.ns.ca
> -------------------

You should be able to get what you want using either a delayed rule, or
Block localization.

In[1]:= u = {{1,2},{3,4},{5,6},{7,8}};

In[2]:= x = 7;

In[3]:= u /. {x_, y_} :> {x}

Out[3]= {{1}, {3}, {5}, {7}}

In[4]:= Block[{x}, u /. {x_, y_} -> {x}]

Out[4]= {{1}, {3}, {5}, {7}}

With a non-delayed rule (lhs -> rhs rather than lhs :> rhs) the
right-hand side of the rule evaluates to its global value before there
is an opportunity to localize anything, and Module treats Rule as a
nested scoping construct and leaves it alone.

Dave Withoff
Wolfram Research



  • Prev by Date: Re: replacement rules in packages
  • Next by Date: New version of Leibniz available
  • Prev by thread: Previous variable affects "/."
  • Next by thread: Re: Previous variable affects "/."