MathGroup Archive 2002

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

Search the Archive

RE: Using a Named Pattern in a Rule

  • To: mathgroup at smc.vnet.net
  • Subject: [mg36285] RE: [mg36278] Using a Named Pattern in a Rule
  • From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
  • Date: Fri, 30 Aug 2002 01:19:10 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

>-----Original Message-----
>From: David Park [mailto:djmp at earthlink.net]
To: mathgroup at smc.vnet.net
>Sent: Thursday, August 29, 2002 7:38 AM
>Subject: [mg36285] [mg36278] Using a Named Pattern in a Rule
>
>
>I would like to match a named pattern in an expression and 
>then square the
>result. But my attempt fails.
>
>Clear[f, g, x, y, a]
>expr = 3*f[x]*g[y] + 2 + x^2;
>
>expr /. a:(f[_]*g[_]) :> a^2
>2 + x^2 + 3*f[x]*g[y]
>
>If I drop the name on the pattern, it matches - but it doesn't 
>do what I
>want.
>
>expr /. f[_]*g[_] :> a^2
>2 + 3*a^2 + x^2
>
>How can I name such a pattern and use it on the rhs of a rule?
>
>David Park
>djmp at earthlink.net
>http://home.earthlink.net/~djmp/
>
>

Dear David,

just don't insist on a single name! 

In[17]:=
expr /. (a : f[_])*(b : g[_]) :> (a*b)^2
Out[17]=
2 + x^2 + 3*f[x]^2*g[y]^2

In[29]:=
3*ff[z]*f[x]*g[y] + 2 + x^2 /. (a : f[_])*(b : g[_]) :> (a*b)^2
Out[29]=
2 + x^2 + 3*f[x]^2*ff[z]*g[y]^2

We might tend to understand this behaviour of the pattern matcher. As Times
has the Flat, Orderless attributes, the components of the pattern have to be
taken apart to match separated subexpressions at the lhs, what should the
pattern variable then designate in the course of this procedure?

Look at the FullForm

In[31]:=
(a : f[_])*(b : g[_]) // FullForm
Out[31]//FullForm=
Times[Pattern[a, f[Blank[]]], Pattern[b, g[Blank[]]]]

compared to 

In[12]:=
a : f[_]*g[_] // FullForm
Out[12]//FullForm=
Pattern[a, Times[f[Blank[]], g[Blank[]]]]


Depending on your real problem...

In[43]:=
expr /. a_?NumericQ *b_ :> a*Times[b]^2
Out[43]=
2 + x^2 + 3*f[x]^2*g[y]^2

...might be a more elegant (but risky) solution (?), 
or perhaps else (more robust if you know the names f,g)...

In[79]:=
expr /. a:(f | g)[___] :> a^2
Out[79]=
2 + x^2 + 3*f[x]^2*g[y]^2

In[139]:=
expr /. a : h_[___] /; MemberQ[{f, g}, h] :> a^2
Out[139]=
2 + x^2 + 3*f[x]^2*g[y]^2


Perhaps a fine way would be

In[74]:=
2 + x^2 + 3 f[x]*g[y] /. 
  HoldPattern[Times[a:(_[___]..)]] :> Times[a]^2
Out[74]=
2 + x^2 + 3*f[x]^2*g[y]^2

but of course this only works if you have at least two factors f[] and g[]
(and no mixed powers of x and y!) In that case come back to something like

In[103]:=
2 + x^2*y^2 + 3*x*y^3*f[x]*g[y] + f[x] /. 
a : (_[___]) :> a^2 /; FreeQ[a, Power | Times]
Out[103]=
2 + x^2*y^2 + f[x]^2 + 3*x*y^3*f[x]^2*g[y]^2


--
Hartmut




  • Prev by Date: Re: matching nested heads
  • Next by Date: Re: DSolve for a system of 3 equations
  • Previous by thread: RE: Using a Named Pattern in a Rule
  • Next by thread: Re: Using a Named Pattern in a Rule