RE: Named Patterns in Switch
- To: mathgroup at smc.vnet.net
- Subject: [mg48972] RE: [mg48945] Named Patterns in Switch
- From: "David Park" <djmp at earthlink.net>
- Date: Fri, 25 Jun 2004 02:58:49 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
Bobby, I did change the foo example from a_. to a_ so the x^2 wouldn't match. But I agree that your formulation is simpler and thank you for it. David Park djmp at earthlink.net http://home.earthlink.net/~djmp/ From: DrBob [mailto:drbob at bigfoot.com] To: mathgroup at smc.vnet.net It seems to me that foo didn't match x^2 properly, and isn't this simpler? foo3[expr_]:=Replace[expr,{(a_.)*x^(n_):>a,(a_.)*y^(n_):>n}] foo3/@{3*x^2,3*y^2,x^2} {3,2,1} foo4[expr_]:= Replace[expr,{a_. b:g[f[_]..]/;FreeQ[a,g[__]|f[_]]:> a g@@(h2/@b),a_. b:f[_]/;FreeQ[a,g[__]|f[_]]:>a h[b]}] foo4/@{x,g[x],3f[x],a g[f[x],f[y],f[z]]} {x,g[x],3 h[f[x]],a g[h2[f[x]],h2[f[y]],h2[f[z]]]} Bobby On Thu, 24 Jun 2004 13:09:16 -0400, David Park <djmp at earthlink.net> wrote: > Thanks to everyone for the suggestions. > > I'm not completely clear in my own mind what I need here, but I think I want > to sharpen it up so that the pattern must match the entire expression. And I > would like to avoid retyping the entire pattern. The following is my > additional modification of the example from the various suggestions. > > foo[expr_] := > With[{patt1 = (a_)*x^(n_), patt2 = (a_)*y^(n_)}, > Switch[expr, > patt1, Replace[expr, patt1 -> a], > patt2, Replace[expr, patt2 -> n], > _, expr]] > > foo /@ {3*x^2, 3*y^2, x^2} > {3, 2, x^2} > > Here is an example more along the lines of my actual problem... > > Clear[foo2] > foo2[expr_] := > With[ > {patt1 = a_. b:g[f[_] ..] /; FreeQ[a, g[__] | f[_]], > patt2 = a_. b:f[_] /; FreeQ[a, g[__] | f[_]]}, > Switch[expr, > patt1, Replace[expr, patt1 :> a g @@ (h2 /@ b)], > patt2, Replace[expr, patt2 -> a h[b]], > _, expr] > ] > > foo2 /@ {x, g[x], 3f[x], a g[f[x], f[y], f[z]]} > {x, g[x], 3 h[f[x]], a g[h2[f[x]], h2[f[y]], h2[f[z]]]} > > David Park > djmp at earthlink.net > http://home.earthlink.net/~djmp/ > >