Re: Using a Named Pattern in a Rule
- To: mathgroup at smc.vnet.net
- Subject: [mg36281] Re: Using a Named Pattern in a Rule
- From: Alexander Dreyer <dreyer at itwm.fhg.de>
- Date: Fri, 30 Aug 2002 01:19:06 -0400 (EDT)
- Organization: Fraunhofer ITWM
- References: <akkd5n$82d$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
David Park wrote: > > 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/ Hello David, the problem is caused by the way how Mathematica stores its expressions: expr // FullForm Plus[2, Power[x, 2], Times[3, f[x], g[y]]] Let's take a closer look on the rules : (a : f[_]*g[_]) :> (a^2) // FullForm RuleDelayed[Pattern[a, Times[f[Blank[]], g[Blank[]]]], Power[a, 2]] (f[c_]*g[b_]) :> (a^2) // FullForm RuleDelayed[Times[f[Pattern[c, Blank[]]], g[Pattern[b, Blank[]]]], Power[a, 2]] It seeams that Mathematica interprets the first one stricter than the second, maybe because of the additional Pattern matching. So the first pattern matches only to a Times operator with two elements and therefore Times[3, f[x], g[y]] is not matched by the first one. A possible way to obtain your desired result is to use a more complicated explicit matching: expr /. (b_*a_?(MatchQ[#, f[_]*g[_]] &)) :> b*(a^2) Sincerely Alexander -- / Alexander Dreyer, Dipl.-Math. - Abteilung Adaptive Systeme \ / Fraunhofer Institut fuer Techno- und Wirtschaftsmathematik (ITWM) \ \ Gottlieb-Daimler-Strasse, Geb. 7^2=49/313 D-67663 Kaiserslautern / \ http://www.itwm.fhg.de Tel.:(0631)205-2851 Fax:(0631)205-4139 /