MathGroup Archive 1992

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

Search the Archive

Re: ReplaceAll feature

  • To: mathgroup at yoda.physics.unc.edu
  • Subject: Re: ReplaceAll feature
  • From: withoff
  • Date: Thu, 8 Oct 92 10:21:05 CDT

> In the following, why is Out[1] different from Out[2] and Out[3]:
> 
> Mathematica 2.0 for SGI Iris
> Copyright 1988-91 Wolfram Research, Inc.
>  -- Terminal graphics initialized --
> 
> In[1]:= (a+b+c+d)/.{a+b->x,c+d->y}
> 
> Out[1]= c + d + x
> 
> In[2]:= (a+b+c+d)/.a+b->x/.c+d->y
> 
> Out[2]= x + y
> 
> In[3]:= (a+b+c+d)//.{a+b->x,c+d->y}
> 
> Out[3]= x + y
> 
> I guess it has something to do with Flat. This is not a big problem, but IF
> it can be easily fixed, it should be fixed. But maybe there are some "deep"
> reasons why it behaves like this ?
> -------------------------------------------------------------------
>   Pekka Janhunen                    tel (+358) 0 1929 535
>   Finnish Meterological Institute   fax (+358) 0 1929 539
>   Geophysics Department             tlx 124436 EFKL SF
>   P.O.BOX 503, SF-00101 Helsinki
>   FINLAND
>   Internet    : Pekka.Janhunen at fmi.fi
>   SPAN & NSI  : 22104::pouta::Pekka.Janhunen     
>   EARN/Bitnet : Pekka.Janhunen%fmi.fi at fingate
>   x.400       : /C=fi/ADMD=Mailnet/PRMD=IL/SUR=Janhunen/GIV=Pekka/    
> -------------------------------------------------------------------

Yes, this does have something to do with Flat.

ReplaceAll[e, rules] (or e /. rules) stops making replacements in
a particular subexpression as soon as a replacement causes the
subexpression to change.

ReplaceAll starts here with the entire expression, a+b+c+d, and applies
the first rule, a+b->x.  Since Plus has attribute Flat, the pattern
matcher looks for combinations of terms in the sum that match the pattern
a+b.  When a match is found, application of the rule causes the expression
to change, so ReplaceAll stops without ever looking at the second rule:

In[10]:= a+b+c+d /. {a+b->x, c+d->y}    

Out[10]= c + d + x

If there are no matches with the entire expression for either rule,
ReplaceAll starts looking at subexpressions.  In the example below,
the first rule (a+b->x) matches the first subexpression (a+b), and no
further rules are applied to that subexpression.  The second rule
(c+d->y) is applied in the same manner to the second subexpression:

In[11]:= {a+b, c+d} /. {a+b->x, c+d->y}

Out[11]= {x, y}

If Replace all is nested, as in ReplaceAll[ReplaceAll[e, r1], r2]
(or e /. r1 /. r2), the inner evaluation, ReplaceAll[e, r1], applies
the first rule, and the outer evaluation applies the second.

Dave Withoff
withoff at wri.com





  • Prev by Date: AllRoots
  • Next by Date: Re: Loop problem
  • Previous by thread: ReplaceAll feature
  • Next by thread: Displaying real numbers