# pattern matching – Simplify the simplification of the Kronecker delta sum

I wrote a function to simplify the sum of the Kronecker delta.

The function assumes that each sum is on all the possible values ​​of the index.

How to simplify the last 3 rules of the function?

These 3 rules are a bit repetitive.

Thanks again.

Function:

``````F[exp_] : = exp //. {(x1_) + (x2 __):> f[x1] + f[x2],
Sum[(x1_) + (x2__), z__]   :> f[Sum[x1, z]]+ f[Sum[x2, z]],
(c __) * Sum[x1__, z__]       :> c * f[Sum[x1, z]],
Sum[Sum[x1__, z1__], z2__]:> f[Sum[x1, z1, z2]],

Sum[(c1___)*KroneckerDelta[r_, s_]* (c2 ___), z1__,
{s_, 1, p_}, z2___]:> f[Sum[c1*c2 /. s -> r, z1, z2]],
Sum[(c1___)*KroneckerDelta[r_, s_]* (c2 ___), z1___,
{s_, 1, p_}, z2__]:> f[Sum[c1*c2 /. s -> r, z1, z2]],
Sum[(c1___)*KroneckerDelta[r_, s_]* (c2 ___),
{s_, 1, p_}]:> f[c1*c2 /. s -> r]}
``````

Test:

``````Test = Sum[A[j, k, l]* KroneckerDelta[j, a]* KroneckerDelta[k, b]*
second[j, k, l, m] +
A[j, k, m]* KroneckerDelta[l, c]* KroneckerDelta[j, a]*
KroneckerDelta[k, b]*
second[j, k, l, m]{j, 1, J}, {k, 1, K}, {l, 1, L}, {m, 1, L}]F[test]
``````