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.

  • 2
    $\begingroup$ Do you want this to work for any head (hence F_) or only certain symbols? $\endgroup$ – mfvonh Jul 19 '14 at 21:08
  • $\begingroup$ 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. $\endgroup$ – Jens Jul 19 '14 at 22:09
  • $\begingroup$ Related: (20540) $\endgroup$ – Mr.Wizard Jul 20 '14 at 7:03

Plus is protected. but you can use unprotect.

F_[1, j___] + F_[2, j___] + F_[3, j___] := 
 Defer@Sum[F[i, j], {i, 1, 3}]
  • $\begingroup$ Will that change the definition of "Plus" forever? $\endgroup$ – Jerald Jul 19 '14 at 21:49
  • $\begingroup$ Just it's effect in after run this code $\endgroup$ – 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]]]);


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

enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.