Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.soft-sys.math.mathematica > #16474
| From | Yi Wang <tririverwangyi@gmail.com> |
|---|---|
| Newsgroups | comp.soft-sys.math.mathematica |
| Subject | Re: Default value in pattern matching |
| Date | 2014-01-24 09:07 +0000 |
| Message-ID | <lbtafl$c70$1@smc.vnet.net> (permalink) |
| References | <20140118095946.3B4C36A11@smc.vnet.net> <lblc64$mic$1@smc.vnet.net> |
| Organization | Time-Warner Telecom |
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@gmail.com>
>
> > To: mathgroup@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.
>
> >
>
> >
Back to comp.soft-sys.math.mathematica | Previous | Next — Previous in thread | Find similar
Re: Default value in pattern matching Larry Adelston <larrya@wolfram.com> - 2014-01-21 08:47 +0000 Re: Default value in pattern matching Yi Wang <tririverwangyi@gmail.com> - 2014-01-24 09:07 +0000
csiph-web