Skip to main content
1 of 3
JuanC97
  • 632
  • 4
  • 12

How to deal with procedurally generated rules and patterns?

I'm trying to procedurally generate replacement rules of the following form

X[{a,a}] -> X1
X[{a,b}]X[{b,a}] -> X2
X[{a,b}]X[{b,c}]X[{c,a}] -> X3
X[{a,b}]X[{b,c}]X[{c,d}]X[{d,a}] -> X4

and I know the number of maximum required replacement rules in advance.


I think it's better to implement {a1___, a2___, a3___, ... } instead of {a,b,c, ... }, this way, the pseudocode reads off

Xn = X[{a[1],a[2]}] X[{a[2],a[3]}]... X[{a[n-1],a[n]}] X[{a[n],a[1]}]
Xn = Product[ X[{a[i],a[i+1]}], {i,1,n-1} ] X[{a[n],a[1]}]

which, translated into actual Mathematica code gives:

MyRule[n_] := 
  a___ Product[ 
    Subscript[X, {Symbol["μ"<>ToString[i]<>"___"], Symbol["μ"<>ToString[i+1]<>"___"]}], 
  {i,1,n-1}] Subscript[X, 
      {Symbol["μ"<>ToString[n]<>"___"], Symbol["μ"<>ToString[1]<>"__"]}
  ] :> a Subscript[X, n]

However, running

Subscript[X, {a, b}] Subscript[X, {b, a}] /. MyRule[2]

shows that this definition is not working properly, seemingly, because of a conflict in the way the dummy indices are written and some issues with their 'Symbol' character. Could someone please clarify how to fix this then?

JuanC97
  • 632
  • 4
  • 12