       Re: Sum pattern

• To: mathgroup at smc.vnet.net
• Subject: [mg128278] Re: Sum pattern
• From: Bob Hanlon <hanlonr357 at gmail.com>
• Date: Wed, 3 Oct 2012 23:38:55 -0400 (EDT)
• Delivered-to: l-mathgroup@mail-archive0.wolfram.com
• Delivered-to: l-mathgroup@wolfram.com
• Delivered-to: mathgroup-newout@smc.vnet.net
• Delivered-to: mathgroup-newsend@smc.vnet.net
• References: <20120930000917.61B1A6865@smc.vnet.net>

```Clear[f]

x = f[a1, s] + f[a2, s] + f[a3, s];

y = f[First /@ x, s]

f[a1 + a2 + a3, s]

To see why your rule didn't work, take it one step at a time

x /. (p : Plus[__f]) -> p

f[a1, s] + f[a2, s] + f[a3, s]

x /. (p : Plus[__f]) -> (First /@ p)

f[a1, s] + f[a2, s] + f[a3, s]

This is where it broke.

Alternatives:

y === (x /. (p : Plus[__f]) ->
f[Map[First, x, {1}], s]/3)

True

y === f[x[[All, 1]], s]

True

y === f[x /. f[a_, s] -> a, s]

True

y === f[Total@Cases[x, f[a_, s] -> a], s]

True

y === f[Plus @@ Cases[x, f[a_, s] -> a], s]

True

y === (x //. f[a_, s] + f[b_, s] -> f[a + b, s])

True

Using UpValues

f /: f[a_, s] + f[b_, s] := f[a + b, s];

y === x

True

Bob Hanlon

On Wed, Oct 3, 2012 at 3:07 AM, Dave Snead <dsnead6 at 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:= x = f[a1, s] + f[a2, s] + f[a3, s]
>
> Out= f[a1, s] + f[a2, s] + f[a3, s]
>
> In:= y = f[First /@ x, s]
>
> Out= f[a1 + a2 + a3, s]
>
> which is what I want.
>
> However when I turn this into a rule
>
> In:= z = x /. (p : Plus[__f]) -> f[First /@ p, s]
>
> Out= 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?
>