Re: Bug in pattern matching?
- To: mathgroup at smc.vnet.net
- Subject: [mg8736] Re: [mg8722] Bug in pattern matching?
- From: Allan Hayes <hay at haystack.demon.co.uk>
- Date: Sat, 20 Sep 1997 22:28:03 -0400
- Sender: owner-wri-mathgroup at wolfram.com
"Peter Strmbeck" <pqst at celsiustech.se>
[mg8722] Bug in pattern matching?
wants to use pattern matching to convert
lst= {a[0],a[1],a[2],a[3],a[4],a[5]};
to
{{a[0]},{C a[1], C a[2], C a[3], C a[4]},{a[5]}}
but notices the result
ls/.{first_, middle___, last_}->{{first},C {middle},{last}}
{{a[0]},{C a[1] a[2] a[3] a[4]},{a[5]}}
Peter:
You need to use :> (RuleDelayed) not -> (Rule)
ls /. {first_, middle___, last_} :>
{{first}, C{middle}, {last}}
{{a[0]},{C a[1],C a[2],C a[3],C a[4]},{a[5]}}
Explanation:
With {first_, middle___, last_}->{{first},C {middle},{last}}
the right side is evaluated to {first, Times[C middle], last}
before any matching and passing of intances of first_, middle___,
and Last are passed to the right. takes place. So we get we get
{{a[1]},{Times[C a[1] a[2] a[3] a[4]]},{a[5]}}.
With {first_, middle___, last_}->{{first},C {middle},{last}}
The matching and passing to the right occurs before any evaluation
of the right, so we first get
{{a[1]}, C {a[1] a[2] a[3] a[4]},a[5]},
and this then evaluates to
{{a[0]},{C a[1],C a[2],C a[3],C a[4]},{a[5]}}
Allan Hayes
hay at haystack.demon.co.uk
http://www.haystack.demon.co.uk/training.html
voice:+44 (0)116 2714198
fax: +44 (0)116 2718642
Leicester, UK