3
$\begingroup$

I would like to replace any function f[x, y, ...] in a certain expression with the same function with all its arguments squared, i.e. f[x^2, y^2, ...]. For example, 2f[x]g[y, z]h[a, b, c] should be replaced with 2f[x^2]g[y^2, z^2]h[a^2, b^2, c^2].

So I tried the following:

h[a, b, c] /. f_[x__] -> f @@ (#^2 & /@ List[x])

However, this does not work as expected. Instead of h[a^2, b^2, c^2] I get h[a^b^c^2]. To be sure, I tried this as a test:

h[a, b, c] /. f_[x__] -> List[x]

The output is {a, b, c}, as expected. So if List[x] is {a, b, c}, I would expect #^2 & /@ List[x] to be {a^2, b^2, c^2}. To make absolutely sure I'm using Map correctly, I tried this:

h[a, b, c] /. f_[x__] -> f @@ (#^2 & /@ {a, b, c})

The result is indeed h[a^2, b^2, c^2] as I expect. So why is the mapping on List[x] not working?

Thanks.

$\endgroup$
3
  • 2
    $\begingroup$ try h[a, b, c] /. f_[x__] :> f @@ ({x}^2) or h[a, b, c] /. f_[x__] :> f @@ (#^2 & /@ List[x])? $\endgroup$ – kglr Jun 24 at 14:17
  • $\begingroup$ try Trace[h[a, b, c] /. f_[x__] -> f @@ (#^2 & /@ List[x])] // Column to see why the versions with -> do not work. $\endgroup$ – kglr Jun 24 at 14:20
  • $\begingroup$ Thanks, Trace is indeed very helpful here. I wasn't aware it existed, but I'm definitely going to use it from now on... $\endgroup$ – CMB Jun 24 at 14:32
5
$\begingroup$

Use RuleDelayed rather than Rule

h[a, b, c] /. f_[x__] :> f @@ (#^2 & /@ {x})

(* h[a^2, b^2, c^2] *)

Or more simply

h[a, b, c] /. f_[x__] :> f @@ ({x}^2)

(* h[a^2, b^2, c^2] *)
$\endgroup$
2
  • $\begingroup$ Perfect, thanks! So just to make sure I understand, the reason Rule didn't work is that it first evaluates the rhs to f[x^2] and only then applies the rule, while RuleDelayed first applies the rule and then evaluates the (correct) rhs? $\endgroup$ – CMB Jun 24 at 14:31
  • $\begingroup$ From the documentation, "lhs -> rhs evaluates rhs immediately" and "lhs :> rhs or lhs :-> rhs represents a rule that transforms lhs to rhs, evaluating rhs only after the rule is used". $\endgroup$ – Bob Hanlon Jun 24 at 14:37

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