MathGroup Archive 2012

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Sum pattern


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[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
>
>
>



  • Prev by Date: Re: Multi Thread in Mathematica (not multi core)
  • Next by Date: Integrating over 3D vector
  • Previous by thread: Re: Sum pattern
  • Next by thread: Re: Sum pattern