Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.math.mathematica

Topic: Pattern Matching with ReplaceRepated Behaving Unexpectedly
Replies: 1   Last Post: Dec 5, 2012 3:10 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View  
Bob Hanlon

Posts: 892
Registered: 10/29/11
Re: Pattern Matching with ReplaceRepated Behaving Unexpectedly
Posted: Dec 5, 2012 3:10 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

The second rule is never seen since the first result matches the first
rule. Note:

{u, a, a, v} //. {
{p___, x : Longest[(a_) ..], q___} :>
(Print["Rule 1 applied"];
{p, a^Length[{x}], q}),
{x___, a^2, y___} :>
(Print["Rule 2 applied"];
{x, e, y})}

Rule 1 applied

Rule 1 applied

{u, a^2, v}

MatchQ[%, {p___, x : Longest[(a_) ..], q___}]

True

You can just reverse the order of the rules

{u, a, a, v} //. {
{x___, a^2, y___} :>
(Print["Rule 1 applied"];
{x, e, y}),
{p___, x : Longest[(a_) ..], q___} :>
(Print["Rule 2 applied"];
{p, a^Length[{x}], q})}

Rule 2 applied

Rule 1 applied

Rule 2 applied

{u, e, v}


Bob Hanlon


On Tue, Dec 4, 2012 at 4:13 AM, Brentt <brenttnewman@gmail.com> wrote:
>
> I'm having trouble understanding how replace repeated works.
>
> I have this expression:
>
> In[1]:= {u,a, a,v} //. {
> {p___, x : Longest[(a_) ..], q___} :> {p, a^Length[{x}], q},
> {x___, a^2, y___} :> {x, e, y}
> }
>
>
> What I think should happen here is that {u,a,a,v} should become {u,a^2,v}
> and then, since ReplaceRepeated should make another pass, {u,a^2,v} should
> become {u,e,v}. And actually if I break up the replacement rules, and
> evaluate them one by one, this is precisely what happens. But when I try to
> put the replacement rules into a list of rules with replace repeated as
> above it just does the first rule and stops. I.e. it outputs
>
> Out[1]:= {u,a^2,v}
>
> Strangely if I do
>
> In[2]:= % //. {
> {p___, x : Longest[(a_) ..], q___} :> {p, a^Length[{x}], q},
> {x___, a^2, y___} :> {x, e, y}
> }
>
> I get the result I expected ReplaceRepeated to give me before
>
> Out[2]:= {u,e,v}
>
>
> I actually thought Replace Repated exists for this very reason, to keep on
> applying the rules until the rules do not change the output any longer, but
> it is failing to do that in this case for some reason even though there
> still seems to be patterns that should be changed?
>
> Can anyone tell me what I am missing here?
>
> Thank you, any help will be greatly appreciated.
>
>





Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.