Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #11975

Re: Sum pattern

From "Dave Snead" <dsnead6@charter.net>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: Sum pattern
Date 2012-10-06 08:13 +0000
Message-ID <k4op83$ink$1@smc.vnet.net> (permalink)
References <20121005064827.40BDA684C@smc.vnet.net>
Organization Time-Warner Telecom

Show all headers | View raw


Thanks everyone,

I've concluded that the shortest way to do this
(in terms of the number of characters I need to type)
which works is:

In[1]:= x = f[a1, s] + f[a2, s] + f[a3, s]

Out[1]= f[a1, s] + f[a2, s] + f[a3, s]

In[3]:= z = x /. (p : Plus[_f, __f]) :> f[First /@ p, s]

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

-- Dave Snead

-----Original Message----- 
From: Fred Simons
Sent: Thursday, October 04, 2012 11:48 PM
Subject: Re: Sum pattern

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



Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread


Thread

Re: Sum pattern "Dave Snead" <dsnead6@charter.net> - 2012-10-06 08:13 +0000

csiph-web