# Simplify rules with variable number of arguments

Problem

How to simplify the following rules?

• The rules simplify (single, double, triple ...) summations of Kronecker delta.

• Replacement should occur if any summation and the Kronecker delta share an index.

The rules

Single summation:

expr /. Sum[y_ KroneckerDelta[r_, s_], {s1_, 1, p1_}] :> (y /. s1 -> r)


Double summation:

expr /. Sum[y_ KroneckerDelta[r_, s_], {s1_, 1, p1_}, {s2_, 1, p2_}] :>
Sum[(y /. s1 -> r), {s2, 1, p2}]


Tripple summation:

Sum[y_ KroneckerDelta[r_, s_], {s1_, 1, p1_}, {s2_, 1, p2_}, {s3_, 1, p3_}] :>
Sum[(y /. s1 -> r), {s2, 1, p2}, {s3_, 1, p3_}]


Test Case

expr0 = Sum[Log[Sum[A[j, k, l]*B[j, k, l], {l, 1, L}]],
{j, 1, J}, {k, 1, K}]
expr = Simplify[D[expr0, A[a, b, c]]]
expr = expr /. Sum[y_ KroneckerDelta[r_, s_], {s_, 1, p_}] :>
(y /. s -> r)
expr = expr /. Sum[y_ KroneckerDelta[r_, s_], {s1_, 1, p1_}, {s2_, 1, p2_}] :>
Sum[(y /. s1 -> r), {s2, 1, p2}]
expr = expr /. Sum[y_ KroneckerDelta[r_, s_], {s_, 1, p_}] :>
(y /. s -> r)


Attempt

I try to replace all the rules with the following rule:

Sum[y_ KroneckerDelta[r_, s_], {s_, 1, p_}, z___] :> Sum[(y /. s -> r), z]


Doesn't work because sum needs at least 2 arguments but z___ can match with nothing. In that case, Sum[(y /. s -> r), z] is a Sum with only 1 argument.

Split the rule into two rules that match with summation over more than 1 index or just over 1 index.

z__ matches with 1 or more arguments.

expr = expr /. Sum[y_ KroneckerDelta[r_, s_], {s_, 1, p_}, z__] :>
Sum[(y /. s -> r), z] /.
Sum[y_ KroneckerDelta[r_, s_], {s_, 1, p_}] :>
(y /. s -> r)