|
[Date Index]
[Thread Index]
[Author Index]
RE: Strange ReplaceAll behavior
- To: mathgroup at smc.vnet.net
- Subject: [mg36810] RE: [mg36774] Strange ReplaceAll behavior
- From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
- Date: Thu, 26 Sep 2002 04:57:24 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
>-----Original Message-----
>From: Lawrence A. Walker Jr. [mailto:lwalker701 at earthlink.net]
To: mathgroup at smc.vnet.net
>Sent: Wednesday, September 25, 2002 7:51 AM
>Subject: [mg36810] [mg36774] Strange ReplaceAll behavior
>
>
>Hi,
>
>For the life of me I am not sure why the following is not
>working in my
>v. 4.2:
>
>ru[a]=a->x;
>f[x_]:=(a+b) /. ru[a];
>
>Why do I get
>f[c] = b+x
>
>and not
>f[c] = b+c?
>
>What gives?
>
>Thanks,
>Lawrence
>
>--
>Lawrence A. Walker Jr.
>http://www.kingshonor.com
>
Lawrence,
in your definition of f, x doesn't show up explicitely. So, in the
evaluation sequence, when the definition for f[c] is applied, no x appears
at rhs i.e.
(a + b) /. ru[a] and such c cannot be inserted. The result is the same as
directly executing
In[11]:= (a + b) /. ru[a]
Out[11]= b + x
If you don't like this, you have to make explicit the Value of ru[a] in the
definiton of f. One way to do so is to use Set instead of SetDelayed:
In[9]:= f[x_] = (a + b) /. ru[a]
Out[9]= b + x
In[10]:= f[c]
Out[10]= b + c
The drawback of this that not only the value of ru[a] is inserted but also
the whole expression including ReplaceAll is evaluated. If this is not
wanted, you have to insert the value of ru[a] into the unevaluated rhs at
the definition. The general means for this are function application, With or
Replace:
In[7]:= (g[x_] := (a + b) /. #) &[ru[a]]
In[8]:= g[c]
Out[8]= b + c
In[16]:= Clear[g]
In[20]:=
Unevaluated[g[x_] := (a + b) /. rule] /. rule -> ru[a]
In[21]:= g[c]
Out[21]= b + c
Here we have to prevent evaluation of the defintion before our rule is
inserted, this is achieved by Unevaluated.
With is a bit more complicated, since the scoping rules for SetDelayed would
not allow the substition of an expression at rhs containing a pattern
variable (the pattern variable is renamed in this case). A simple answer to
this is to also substitute the argument variable (the pattern):
In[31]:= Clear[g]
In[32]:=
With[{rule = ru[a], arg = x_}, g[arg] := (a + b) /. rule]
In[33]:= g[c]
Out[33]= b + c
--
Hartmut Wolf
Prev by Date:
Re: Re: How do I pick out the expression under a radical?
Next by Date:
Mathematica 4.1 and MacOSX 10.2
Previous by thread:
RE: Strange ReplaceAll behavior
Next by thread:
Re: Strange ReplaceAll behavior
|