# Permute a list of elements given a pattern

I have this function f and a pattern

pattern = f[h[x]]f[h[y]]


where h is a generic function. Now, I have a set of two distinct functions list = {h1,h2}

How can I generate a function F[pattern_, list_] which returns the following result?

F[pattern,list]
(* f[h1[x]]f[h2[y]]+f[h2[x]]f[h1[y]] *)

• Is this supposed to work for any pattern with any number of h-functions? Commented Mar 6, 2018 at 19:57
• Yes, You can have for example the patter pattern=f[g[h[x]]]f[h[y]] Commented Mar 6, 2018 at 20:00

First we define a replacement rule that replaces each occurrence of an expression with another expression:

replaceIteratively[expr_, x_, list_] := Module[{n = 0},
expr /. x :> (n++; list[[n]])
]


such that, e.g.,

replaceIteratively[{x, x, k, x}, x, {a, b, c}]
(* {a, b, k, c} *)


Then, F can be defined as

F[pattern_, x_, list_] :=
Total@Table[
replaceIteratively[pattern, x, newh],
{newh, Permutations[list]}
]


such that

F[f[h[x]] f[h[y]], h, {h1, h2}]
(* f[h1[y]] f[h2[x]] + f[h1[x]] f[h2[y]] *)


and

F[f[g[h[x]]] f[h[y]], h, {h1, h2}]
(* f[g[h2[x]]] f[h1[y]] + f[g[h1[x]]] f[h2[y]] *)


The ordering is not as in your example, but this does not matter since + is commutative.

• Thanks you! this solved my problem Commented Mar 6, 2018 at 20:12