Re: Default value in pattern matching

• To: mathgroup at smc.vnet.net
• Subject: [mg132255] Re: Default value in pattern matching
• From: Yi Wang <tririverwangyi at gmail.com>
• Date: Fri, 24 Jan 2014 04:20:18 -0500 (EST)
• Delivered-to: l-mathgroup@mail-archive0.wolfram.com
• Delivered-to: l-mathgroup@wolfram.com
• Delivered-to: mathgroup-outx@smc.vnet.net
• Delivered-to: mathgroup-newsendx@smc.vnet.net
• References: <20140118095946.3B4C36A11@smc.vnet.net> <lblc64\$mic\$1@smc.vnet.net>

```Hi, Larry,

Thanks a lot for your reply! This works for this example, but not exactly in the way I wanted. Because eventually my purpose is not using myPlus to re-implement Plus. But instead I would need myPlus to be some other functions.

With your code, when tracing the evaluation, we have

Trace[a /. {a + myPlus[b_.] -> "matched"}]

{{{{{myPlus[b_.], b_.}, a + (b_.)}, a + (b_.) -> matched, a + (b_.) -> \
matched}, {a + (b_.) -> matched}}, a /. {a + (b_.) -> matched}, \
matched}

Thus first a + myPlus[b_.] is transformed into a+b_., and then comes the "magic" of default value in Plus (which is exactly the thing I want to understand).

If we use HoldPattern, then the above no longer match:

a /. {a + HoldPattern[myPlus[b_.]] -> "matched"}

Out[] = a

To compare, the default value of Plus itself works even for HoldPattern:

a /. {a + HoldPattern[b_.] -> "matched"}

Out[] = "matched"

Best,
Yi

> Don't you need to define myPlus[b_.]?
>
>
>
> In[173]:= myPlus[b_.] = b;
>
> Default[myPlus] = 0;
>
> myPlus[0] := 0;
>
> a /. {a + myPlus[b_.] -> "matched"}
>
>
>
> Out[176]= "matched"
>
>
>
>
>
> Larry
>
>
>
> ----- Original Message -----
>
> > From: "Yi Wang" <tririverwangyi at gmail.com>
>
> > To: mathgroup at smc.vnet.net
>
> > Sent: Saturday, January 18, 2014 3:59:46 AM
>
> > Subject: Default value in pattern matching
>
> >
>
> > Hello,
>
> >
>
> > I was investigating the usage of the "a_." pattern. I understand that f=
or
>
> > some built-in functions with default value, we can do
>
> >
>
> > In[] := a /. {a + b_. -> "matched"}
>
> >
>
> > Out[] = "matched"
>
> >
>
> > However, if I define a function myself with
>
> >
>
> > In[] := Default[myPlus] = 0;
>
> >         myPlus[0] := 0;
>
> >         a /. {a + myPlus[b_.] -> "matched"}
>
> >
>
> > Out[] = a
>
> >
>
> > In other words, my default value is not used in the "b_." pattern. Is t=
here a
>
> > way to get a /. {a + myPlus[b_.] -> "matched"} match in the same way as=
a /.
>
> > {a + b_. -> "matched"}?
>
> >
>
> > Otherwise I have to write separately as
>
> >
>
> > In[] := a /. {a -> "matched", a + myPlus[b_] -> "matched"}
>
> >
>
> > This is a lot of additional work for complicated cases.
>
> >
>
> >

```

• Prev by Date: Re: How to show 1+2+3+ ... = -1/12 using
• Next by Date: Re: Part Function
• Previous by thread: Re: Default value in pattern matching
• Next by thread: Re: Default value in pattern matching