# Collapsing summation

I am trying to write a command to collapse the sum of terms into an expression with summation. Something like

F_[1, j___] + F_[2, j___] + F_[3, j___] := Sum[F[i, j], {i, 1, 3}]


which is designed to to collapse the LHS, which is a function of 2 or more parameters (for example - F[i,j] or F[i,j,k] - this is the reason for the i___ in the definition) into a summation on the first variable. but I get the following error:

SetDelayed::write: "Tag Plus in F_[1,i___]+F_[2,i___]+F_[3,i___] is Protected"


It seems that I am overriding the Plus definition. I don't know then how to define this properly. Thanks.

• Do you want this to work for any head (hence F_) or only certain symbols? – mfvonh Jul 19 '14 at 21:08
• In addition to the question @mfvonh asked, you should also specify what to do with cases like F[1,i]+F[2,i]+F[3,i] where i would appear as the summation index and as an external variable. That doesn't look like a replacement I would want to make in general. The answer would probably use UpSetDelayed, not unprotecting Plus. – Jens Jul 19 '14 at 22:09
• Related: (20540) – Mr.Wizard Jul 20 '14 at 7:03

Plus is protected. but you can use unprotect.

Unprotect[Plus];
F_[1, j___] + F_[2, j___] + F_[3, j___] :=
Defer@Sum[F[i, j], {i, 1, 3}]
Protect[Plus];

• Will that change the definition of "Plus" forever? – Jerald Jul 19 '14 at 21:49
• Just it's effect in after run this code – Junho Lee Jul 20 '14 at 4:28

I think you may find value in this rule:

sequentialQ[x_List] := x == Range[x[[1]], x[[-1]]]

rule =
HoldPattern[Plus[s : F_[_, j___] ..]] /;
sequentialQ @ {s}[[All, 1]] :>
(HoldForm[Sum[F[i, j], {i, ##}]] & @@ {Min@#, Max@#} &[{s}[[All, 1]]]);


Test:

F[1.0, q, r] + F[1.5, q, r] + F[2, q, r] + F[2.7, q, r] + F[3.0, q, r] /. rule