# Symbolically replace part of expression if that expression meets a condition

Say I have an expression like

expr = g1[i1, j1] h1[k, l] f1[i, j1, k1, l] + g2[k1, j] f2[i, l, k1, l1] + f3[i, j, l, l1] + ...

and in each term above I want to do some transformations such that the f functions inputs are f[i,j,k,l]. For example one transformation for the f2 term would be {l->j, j->l}, changing the f2 term to g2[k1, l] f2[i, j, i, l1]. Note that the inputs of the other functions in the same term must also undergo the same transformations.

I've been attempting this by doing something along the lines of

patt = pre_. f_[I1_,I2_,I3_,I4_] post_.
Map[(# // With[{
I1 = Cases[{#}, patt -> I1][[1]],
I2 = Cases[{#}, patt -> I2][[1]],
I3 = Cases[{#}, patt -> I3][[1]],
I4 = Cases[{#}, patt -> I4][[1]]},
Which[
!(I1 === i), ReplaceAll[{i -> I1, I1 -> i}],
!(I2 === j), ReplaceAll[{j -> I2, I2 -> j}],
!(I2 === k), ReplaceAll[{k -> I3, I3 -> k}],
!(I2 === l), ReplaceAll[{l -> I4, I4 -> l}],
]]) &, expr]


The idea here is to, on a term by term basis, identify the input positions which are incorrect and flip what's in that position with the correct symbol.

This might work if Which went through all the conditionals rather than stopping on the first one and if I had something to chain apply the resulting list of ReplaceAll functions. Case does not seem to to be the right tool to use here either, but after scouring the documentation for a more appropriate function I came up with nothing.

• Something like: Replace[expr, subexpr : ___ f2[___] :> Replace[subexpr, {l -> j, j -> l}, {2}], {1}]? – user31159 Sep 19 '16 at 11:42
• Thank you, the : was just what I needed. Currently my solution to this problem is Replace[expr, subexpr : pre_. f_[I1_, I2_, I3_, I4_] post_. :> ReplaceAll[subexpr, {i -> I1, I1 -> i, j -> I2, I2 -> j, k -> I3, I3 -> k, l -> I4, I4 -> l}], {1}] – alessandro Sep 20 '16 at 2:39

expr = g1[i1, j1] h1[k, l] f1[i, j1, k1, l] + g2[k1, j] f2[i, l, k1, l1] + f3[i, j, l, l1]

Replace[expr, subexpr : ___ f2[___] :> Replace[subexpr, {l -> j, j -> l}, {2}], {1}]