Re: Replacement question
- To: mathgroup at smc.vnet.net
- Subject: [mg35132] Re: [mg35114] Replacement question
- From: Sseziwa Mukasa <mukasa at jeol.com>
- Date: Tue, 25 Jun 2002 19:55:06 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
On Tuesday, June 25, 2002, at 03:41 AM, ginak wrote: > Suppose I have something like > > In [100] := h[3]/f[2.33342] > > Out[100] := 24.12711 > > and now I want to evaluate h[5]/f[2.33342], i.e. the same as in > In[100] but replaceing h[3] with h[5]. This won't work > > In [101] := In[100] /. h[3]->h[5] > > Out[101] := 24.12711 > > because In[100] is fully evaluated to 24.12711 before the rule is > applied. (Generally, the expressions I'm interested in are more of a > pain to type than h[5]/f[2.33342]). How do I tell Mathematica to > evaluate > In[100] only enough to apply the given substition rule, apply the > substitution rule, and only then proceed with the evaluation? > > In fact, I don't even know how to do a replacement like > > In [102] := h[3]/f[2.33342] /. h[3]->h[5] > > for the same reason: the LHS is evaluated before the rule can be > applied. (Of course, in this case this replacment task is pointless, > since it is so easy to type out the desired expression, but there are > situations in which one can obtain a complicated expression by cutting > and pasting, and wants to apply a substitution rule to the complicated > expression before Mathematica evaluates it.) > > As far as I can tell the two situations are slightly different. In the case of the expression In[100]/.h[3]->h[5], In[100] evaluates using the value of h[3] before the rule gets applied, so the expression that the rule is being applied to is not h[3]/f[2.33342] but the value of that expression. The following block removes the downvalues of h so that h[3] does not evaluate, then restores the downvalues and evaluates the resulting expression: Block[{dv=DownValues[h]},h[x_]=.;expr=In[401]/.h [3]->h[5];DownValues[h]=dv;expr] In the other case you simply need to use HoldPattern to prevent the left hand side of the rule from evaluating h[3]/f[2.33342]/.HoldPattern[h[3]]->h[5] There may be a simpler way to handle the first case but I can't think of it right now. Regards, Ssezi