Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1997
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1997

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

Search the Archive

Re: Bug in pattern matching?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg8746] Re: [mg8722] Bug in pattern matching?
  • From: David Withoff <withoff>
  • Date: Sat, 20 Sep 1997 22:28:12 -0400
  • Sender: owner-wri-mathgroup at wolfram.com

> I'm trying to "deconstruct" a list, perform an operation to a pert of the
> list and then recombine the result. When I did this I found out that
> multiplication in pattern matching performs differently than otherwise.
> 
> Check version:
> 
> In[1]:=
> $Version
> Out[1]=
> "Microsoft Windows 3.0 (October 6, 1996)"
> 
> Define list:
> 
> In[2]:=
> ls=Table[a[j], {j,0,5}]
> Out[2]=
> {a[0],a[1],a[2],a[3],a[4],a[5]}
> 
> I want to split this list into the following three sublists: 
> 
> {a[0],a[1],a[2],a[3],a[4],a[5]} -> {a[0]}, {a[1], a[2], a[3], a[4]}, {a[5]}
> 
> Use pattern matching:
> 
> In[3]:=
> ls/.{first_, middle___, last_}\[Rule] {{first},{middle},{last}}
> Out[3]=
> {{a[0]},{a[1],a[2],a[3],a[4]},{a[5]}}
> 
> This works fine. Now I want to multiply the middle list by a factor C.
> Ordinary multiplication works like this:
> 
> In[4]:=
> C ls
> Out[4]=
> {C a[0],C a[1],C a[2],C a[3],C a[4],C a[5]}
> 
> Doing this in a pattern matching statement produces a totally different
> result:
> 
> In[5]:=
> ls/.{first_, middle___, last_}\[Rule] {{first},C {middle},{last}}
> Out[5]=
> {{a[0]},{C a[1] a[2] a[3] a[4]},{a[5]}}
> 
> The middle list now contains a completely different result than Out[4]!
> 
> Can anyone please explain this to me?
> 
> /Peter Strömbeck

Try using a delayed rule (lhs:>rhs rather than lhs->rhs), as in

In[1]:= ls=Table[a[j], {j,0,5}]

Out[1]= {a[0], a[1], a[2], a[3], a[4], a[5]}

In[2]:= ls/.{first_, middle___, last_} :> {{first},C {middle},{last}}

Out[2]= {{a[0]}, {C a[1], C a[2], C a[3], C a[4]}, {a[5]}}

If a non-delayed rule is used here then the right-hand side of the
rule is evaluated before anything else, so the rule that gets
applied is actually

    {first_, middle___, last_} :> {{first}, {C middle},{last}}

which is not what you want.  With this rule, the sequence of expressions
that match "middle" gets inserted into a product, rather than as elements
of a list.

This example (and examples like it) are the most common reason
for using delayed rules.

Dave Withoff
Wolfram Research


  • Prev by Date: Re: Bug in pattern matching?
  • Next by Date: Re: Bug in pattern matching?
  • Previous by thread: Re: Bug in pattern matching?
  • Next by thread: Re: Bug in pattern matching?