# Why does ExpandAll not work within a symbolic sum?

If I evaluate Sum[(x + Subscript[y, n])^2, n] + (y + z)^2 // ExpandAll then the expression within the Sum is not expanded, yet if it is replaced with another function such as Sin the inner expression is expanded. Why is this the case and how do I get the desired behaviour?

Inactivate might be helpful here:

exp = Inactivate[Sum[(x + y[n])^2, n] + (y + z)^2, Sum];

Activate[ExpandAll[exp]]
(*y^2 + 2*y*z + z^2 + Sum[x^2 + 2*x*y[n] + y[n]^2, n]*)


It doesn't work because Sum has the attribute HoldAll. You can see this effect with a made-up function,

ClearAll@fg
(fg[(x + y[n])^2, n] + (y + z)^2) // ExpandAll
SetAttributes[fg, HoldAll];
(fg[(x + y[n])^2, n] + (y + z)^2) // ExpandAll
(* y^2 + 2 y z + z^2 + fg[x^2 + 2 x y[n] + y[n]^2, n] *)
(* y^2 + 2 y z + z^2 + fg[(x + y[n])^2, n] *)


(I replaced your Subscript[y,n] with y[n] because subscripts are bad mmkay) Before fg had the attribute, ExpandAll worked just as hoped, but with the attribute you can not expand within fg. I don't see a way to remove this attribute, nor an easy workaround. Here is something that works though,

ClearAll@f;
(Sum[(x + y[n])^2, n] + (y + z)^2) // # /. Sum -> f & //
ExpandAll // # /. f -> Sum &
(* y^2 + 2*y*z + z^2 + Sum[x^2 + 2*x*y[n] + y[n]^2, n] *)

• If one must: MapAt[ExpandAll, Sum[(x + y[n])^2, n], 1]. Mar 23 '16 at 13:27
• But MapAt[ExpandAll, Sum[(x + y[n])^2, n] + (y + z)^2, {1}] doesn't do the trick, you have to resort to mapping MapAt, MapAt[ExpandAll, #, 1] & /@ (Sum[(x + y[n])^2, n] + (y + z)^2) Mar 23 '16 at 13:32
• Yes, it was intended as a special treatment for Sum[] objects. Mar 23 '16 at 13:33