MathGroup Archive 2004

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

Search the Archive

RE: Named Patterns in Switch

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_)},
    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...

foo2[expr_] :=
    {patt1 = a_. b:g[f[_] ..] /; FreeQ[a, g[__] | f[_]],
     patt2 = a_. b:f[_] /; FreeQ[a, g[__] | f[_]]},
      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

From: DrBob [mailto:drbob at]
To: mathgroup at

How's this?




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

> 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
> 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
> David Park
> djmp at

DrBob at

  • 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