Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
NCTM or The Math Forum.


Yi Wang
Posts:
33
Registered:
3/30/12


Re: Default value in pattern matching
Posted:
Jan 24, 2014 4:07 AM


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 reimplement 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 builtin 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. > > > > > >



