Say I have an expression:
f[a, f[a, b]]
I would like to replace each a
with either x
or y
. By using Replace
, I can do
Replace[f[a, f[a, b]], {{a -> x}, {a -> y}}, All]
Which gives
{ f[x, f[x, b]], f[y, f[y, b]] }
However, I'd like to get (in any order)
{ f[x, f[x, b]], f[x, f[y, b]], f[y, f[x, b]], f[y, f[y, b]] }
Essentially, each term is considered separately.
I've tried looking in the documentation for functions similar to Replace
, but to no avail. How do I go about this? Thanks in advance!
Edit
I feel I should've been more precise in my original question. For some nested expression like f[x, f[x, x]]
, I need a list of expressions where some (or all or none) of the f
's are replaced by g
's. Only f
's which take x
as their first argument may be replaced; the rest are left unchanged.
For example, an input of
f[f[x, x], x]
Should give (in any order)
{ f[f[x, x], x], f[g[x, x], x] }
Notice how the first f
has not been replaced, since it does not have x
as its first argument.
I hope that this rephrasing is not distruptive. If I should instead ask this as a separate question, please tell me!
Map[f[#[[1]],f[#[[2]],b]]&,Tuples[{x,y},2]]
instantly gives you the list of results{f[x,f[x,b]], f[x,f[y,b]], f[y,f[x,b]], f[y,f[y,b]]}
$\endgroup$ – Bill Aug 21 '19 at 17:00replacePerTerm
? $\endgroup$ – ryuku Aug 21 '19 at 17:32