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[h1[x]]f[h2[y]]+f[h2[x]]f[h1[y]] *)
  • $\begingroup$ Is this supposed to work for any pattern with any number of h-functions? $\endgroup$ – JEM_Mosig Mar 6 '18 at 19:57
  • $\begingroup$ Yes, You can have for example the patter pattern=f[g[h[x]]]f[h[y]] $\endgroup$ – apt45 Mar 6 '18 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_] := 
  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]] *)


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.

  • $\begingroup$ Thanks you! this solved my problem $\endgroup$ – apt45 Mar 6 '18 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.