1
$\begingroup$

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

1 Answer 1

2
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ Thanks you! this solved my problem $\endgroup$
    – apt45
    Commented Mar 6, 2018 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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