0

Question

I try to define a function that apply a set of rules to an expression in Mathematica 11.3.

However, the function returns a result that is not the same as directly applying the rule to the expression.

How to define the function correctly?

Thanks again.

Expression

expr2 = Sum[
  A[j, k, l, m]*KroneckerDelta[l, a]*KroneckerDelta[j, b]*
   KroneckerDelta[k, c], {j, 1, J}, {k, 1, K}, {l, 1, K}, {m, 1, K}]

Transform with function

SimplifyKronecker[
  x_] = x //. {Sum[y_ KroneckerDelta[r_, s_], z1_, {s_, 1, p_}, 
      z2___] :> Sum[(y /. s -> r), z1, z2], 
    Sum[y_ KroneckerDelta[r_, s_], z1___, {s_, 1, p_}, z2_] :> 
     Sum[(y /. s -> r), z1, z2], 
    Sum[y_ KroneckerDelta[r_, s_], {s_, 1, p_}] :> (y /. s -> r)}

SimplifyKronecker[expr2]

result: $\sum _{j=1}^J \sum _{k=1}^K \sum _{l=1}^K \sum _{m=1}^K \delta _{a,l} \delta _{b,j} \delta _{c,k} A(j,k,l,m)$

Directly apply rule

expr2 //. {Sum[y_ KroneckerDelta[r_, s_], z1_, {s_, 1, p_}, 
      z2___] :> Sum[(y /. s -> r), z1, z2], 
    Sum[y_ KroneckerDelta[r_, s_], z1___, {s_, 1, p_}, z2_] :> 
     Sum[(y /. s -> r), z1, z2], 
    Sum[y_ KroneckerDelta[r_, s_], {s_, 1, p_}] :> (y /. s -> r)}

result: $\sum _{m=1}^K A(b,c,a,m)$

R zu
  • 349
  • 1
  • 8
  • Yo missed a colon in definition of the simplifying function: SimplifyKronecker[ x_] := x //. {Sum[y_ KroneckerDelta[r_, s_], z1_, {s_, 1, p_}, z2___] :> Sum[(y /. s -> r), z1, z2], Sum[y_ KroneckerDelta[r_, s_], z1___, {s_, 1, p_}, z2_] :> Sum[(y /. s -> r), z1, z2], Sum[y_ KroneckerDelta[r_, s_], {s_, 1, p_}] :> (y /. s -> r)} – yuriyi Nov 21 '18 at 07:59
  • well, if you used a colon, you would get the desired result – yuriyi Nov 21 '18 at 08:08
  • because colon delays the evaluation. check here Immediate and Delayed Definitions – yuriyi Nov 21 '18 at 08:11
  • Defining a similar function for a similar set of rules work without :=: https://mathematica.stackexchange.com/a/186409/61476 Since := hurts performance, is it possible to avoid it here? – R zu Nov 21 '18 at 08:17
  • When you do not use the colon, SimplifyKronecker[x] simply returns x because it has already been evaluated. defining the function with a colon won't hurt performance in your case since without it function does nothing. – yuriyi Nov 21 '18 at 08:21

0 Answers0