RE: Named Patterns in Switch

• To: mathgroup at smc.vnet.net
• Subject: [mg48963] RE: [mg48945] Named Patterns in Switch
• From: "David Park" <djmp at earthlink.net>
• Date: Fri, 25 Jun 2004 02:58:35 -0400 (EDT)
• Sender: owner-wri-mathgroup at wolfram.com

```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

From: DrBob [mailto:drbob at bigfoot.com]
To: mathgroup at smc.vnet.net

How's this?

foo[expr_]:=expr/.{(a_.)*x^(n_):>a,(a_.)*y^(n_):>n}
foo[3*x^3]

3

Bobby

On Thu, 24 Jun 2004 05:36:29 -0400 (EDT), David Park <djmp at earthlink.net>
wrote:

> Dear MathGroup,
>
> Here is an attempted routine using Switch that does not work.
>
> foo[expr_] :=
>  Switch[expr,
>         (a_.)*x^(n_), a,
>         (a_.)*y^(n_), n]
>
> foo[3*x^3]
> a			(I was hoping for 3)
>
>
> Switch uses patterns, but any named patterns are useless. So the a in the
third argument in Switch has nothing to do with the a_. in the second
argument.
>
> Is there some Mathematica construction that will test successive patterns
with names, do a calculation with the first match and use the names in the
patterns?
>
> David Park
>
>
>
>

--
DrBob at bigfoot.com
www.eclecticdreams.net/index.html

```

• Prev by Date: Re: faster sublist checking
• Next by Date: RE: Named Patterns in Switch
• Previous by thread: RE: Named Patterns in Switch
• Next by thread: RE: Named Patterns in Switch