RE: Named Patterns in Switch

• To: mathgroup at smc.vnet.net
• Subject: [mg48956] RE: [mg48945] Named Patterns in Switch
• From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
• Date: Fri, 25 Jun 2004 02:58:20 -0400 (EDT)
• Sender: owner-wri-mathgroup at wolfram.com
• Thread-topic: [mg48945] Named Patterns in Switch

```>-----Original Message-----
>From: David Park [mailto:djmp at earthlink.net]
To: mathgroup at smc.vnet.net
>Sent: Thursday, June 24, 2004 11:36 AM
>To: mathgroup at smc.vnet.net
>Subject: [mg48956] [mg48945] Named Patterns in Switch
>
>
>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
>
>
>
>

Dear David,

simply I can't guess what you finally want to attain. Perhaps just try a different idiom:

In[16]:= bar[expr_] :=
Replace[expr, {(a_.)*x^(n_) :> a, (a_.)*y^(n_) :> n}]

In[17]:= bar[3*x^4]
Out[17]= 3

In[18]:= bar[3*y^4]
Out[18]= 4

Of course the defaults were different, however you could arrange for that.

The reason for your idea to not work appears to be that you're leaving the scope of definition of the pattern variable a.

If I try to mimik the semantics of Switch (again, except for the default)

In[24]:= baz[expr_] := xSwitch[expr, (a_.)*x^(n_), a, (a_.)*y^(n_), n]

In[22]:= SetAttributes[xSwitch, HoldRest]

In[122]:= xSwitch[expr_, sw__] :=
With[{sw2 = Transpose[Partition[{Hold /@ Unevaluated[sw]}, 2]]},
Which @@ Flatten[
Transpose[MapAt[Map[MatchQ[expr, #] &, #, {2}] &, sw2, 1]]], Hold]]

In[123]:= baz[3 x^4]
Out[123]=
Hold[Which[(MatchQ[3*x^4, #1] & )[(a_.)*x^n_], a,
(MatchQ[3*x^4, #1] & )[(a_.)*y^n_], n]]

I then get the same

In[127]:= baz[3 x^4] // ReleaseHold
Out[127]= a

Here again the pattern variable is confined in scope to the test within MatchQ, to exploit its value we have to use a transformation rule.

cheers,
Hartmut

```

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