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: Sum pattern
Replies: 6   Last Post: Oct 5, 2012 2:41 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Simons, F.H.

Posts: 107
Registered: 12/7/04
Re: Sum pattern
Posted: Oct 5, 2012 2:39 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

On Oct 3, 12:12 am, "Dave Snead"<dsne...@charter.net> wrote:

> Hi,
>
> I'm trying to put together a rule whose left hand side is a sum of arbitrary
> length whose elements all have the same head f.
>
> For example:
>
> In[4]:= x = f[a1, s] + f[a2, s] + f[a3, s]
>
> Out[4]= f[a1, s] + f[a2, s] + f[a3, s]
>
> In[6]:= y = f[First /@ x, s]
>
> Out[6]= f[a1 + a2 + a3, s]
>
> which is what I want.
>
> However when I turn this into a rule
>
> In[7]:= z = x /. (p : Plus[__f]) -> f[First /@ p, s]
>
> Out[7]= f[f[a1, s], s] + f[f[a2, s], s] + f[f[a3, s], s]
>
> Why isn't z equal to y?
> How can I make this rule work?
>
> Thanks in advance,
> Dave Snead


Your solution is almost correct, but fails since you did not take into account that both sides of your rule are evaluated before it is applied.

In[1]:= (p:Plus[__f])->f[First/@p,s]
Out[1]= p__f->f[p,s]

Your rule wraps every expression with head f in another f, as you see in your output.

To prevent the evaluation, use RuleDelayed for keeping the right-hand side and HoldPattern for the left-hand side:


In[2]:= x=f[a1,s]+f[a2,s]+f[a3,s]
x /. (p:HoldPattern[Plus[__f]]):>f[First/@p,s]

Out[2]= f[a1,s]+f[a2,s]+f[a3,s]
Out[3]= f[a1+a2+a3,s]

Fred Simons
Eindhoven University of Technology





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.