MathGroup Archive 2004

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

Search the Archive

Re: Baffled By Underscore Pattern Matching

In order to fit the pattern in In[5], h needs to enclose two identical
arguments to fit the two uses of x. a, b, and c can be any number of
arguments -- even zero. So In[6] can be matched to the pattern in two
different ways:

If x=2, then a must be Sequence[], b must be 3, and c must be
Sequence[4,5,3]. That's the match that explains Out[6].

x=3 is another possibility. In that case a=2, b=Sequence[2,4,5], and

The pattern-matcher found the x=2 match first and didn't look for
another. That's understandable, I think.

If you have a preference in situations like this, it may be possible
to express it. Suppose, for example, you prefer matches that have
c=Sequence[], rather than matches that have a=Sequence[]. In that
case, define it this way:

h[a___,x_,b___,x_]:=hh[x] h[{a},{b},{}]
h[a___,x_,b___,x_,c___]:=hh[x] h[{a},{b},{c}]

h[{2},{2,4,5},{}] hh[3]

h[{},{3},{4,5,7}] hh[2]

Choosing the one with largest argument for hh (for instance) will take
more work, but it might be done by taking care of all the ways
multiple matches can occur. Have fun with that!


Harold.Noffke at (Harold Noffke) wrote in message news:<bvl8su$t50$1 at>...
> MathGroup:
> In my study of Mathematica 5.0, I have reached "The Mathematica Book >
> Principals of Mathematica > Patterns > 2.3.8 Functions with Variable
> Numbers of Arguments".  The In[1]/Out[1] example I understand, but the
> In[2,3]/Out[3] example (discussed below) has me totally mystified.
> As printed, we have ...
> 	In[2]:= h[a___, x_, b___, x_, c___] := hh[x] h[a, b, c]
> 	In[3]:= h[2, 3, 2, 4, 5, 3]
> 	Out[3]= h[4, 5] hh[2] hh[3]
> Now let's make a change to In[2] ...
> 	In[4]:= Clear[h, hh]
> 	In[5]:= h[a___, x_, b___, x_, c___] := hh[x] h[{a}, {b}, {c}]
> 	In[6]:= h[2, 3, 2, 4, 5, 3]
> 	Out[6]= h[{}, {3}, {4, 5, 3}] hh[2]
> I did a Trace on this pattern match problem, and found only that
> doublets were pulled out on each iteration.  In order to understand
> what is happening here, I think I need to understand the matching
> process at a level of granularity finer than Trace can supply.  I
> don"t have a clear mental picture of how In[5] manipulates the number
> stream which feeds into it from In[6].  I have no idea of how the
> In[6] lists came to contain the numbers they do.
> Any help, pointers to tutorial papers, or more illuminating examples
> will be greatly appreciated.
> Thanks.
> Harold

  • Prev by Date: Re: Baffled By Underscore Pattern Matching
  • Next by Date: RE: Defining a function in module problem?
  • Previous by thread: Re: Baffled By Underscore Pattern Matching
  • Next by thread: RE: Baffled By Underscore Pattern Matching