10
$\begingroup$

Suppose I have solved a system of equations, resulting in a solution of the form:

sol = {{f[a1] -> SomeComplicatedFunction[x, a1]}, {f[a2] -> SomeComplicatedFunction[x, a2]}, {f[a3] -> SomeComplicatedFunction[x, a3]}}

I want to use the list of substitutions sol later on, but first I want to apply some method myFunction to the rhs of the substitution. I.e., the desired output is

sol = {{f[a1] -> myFunction[SomeComplicatedFunction[x, a1]]}, {f[a2] -> myFunction[SomeComplicatedFunction[x, a2]]}, {f[a3] -> myFunction[SomeComplicatedFunction[x, a3]]}}

I have tried extracting all the RHSs from sol, applying myFunction to the list, then setting this back to the original f[]s, but this seems to be very inefficient. Is there some canonical Mathematica way of applying rules to solutions while keeping the solutions intact?

$\endgroup$

4 Answers 4

11
$\begingroup$
sol = {
   {f[a1] -> SomeComplicatedFunction[x, a1]},
   {f[a2] -> SomeComplicatedFunction[x, a2]},
   {f[a3] -> SomeComplicatedFunction[x, a3]}};

sol2 = sol /. Rule[lhs_, rhs_] :> Rule[lhs, myFunction[rhs]]

(* {{f[a1] -> myFunction[SomeComplicatedFunction[x, a1]]}, {f[a2] -> 
   myFunction[SomeComplicatedFunction[x, a2]]}, {f[a3] -> 
   myFunction[SomeComplicatedFunction[x, a3]]}} *)
$\endgroup$
9
$\begingroup$

Additional alternatives:

You can use MapAt to map myFunction at positions {All, -1, -1}:

sol3 = MapAt[myFunction, {All, -1, -1}] @ sol

{{f[a1] -> myFunction[SomeComplicatedFunction[x, a1]]},
{f[a2] -> myFunction[SomeComplicatedFunction[x, a2]]},
{f[a3] -> myFunction[SomeComplicatedFunction[x, a3]]}}

You can assign new values at desired positions using Part assignment:

sol4 = sol;
sol4[[All, -1, -1]] = myFunction /@ sol4[[All, -1, -1]];
sol4

same result

$\endgroup$
1
$\begingroup$

You can also replace SomeComplicatedFunction with the composition of myFunction and SomeComplicatedFunction:

sol /. SomeComplicatedFunction -> myFunction @* SomeComplicatedFunction
{{f[a1] -> myFunction[SomeComplicatedFunction[x, a1]]}, 
 {f[a2] -> myFunction[SomeComplicatedFunction[x, a2]]},
 {f[a3] -> myFunction[SomeComplicatedFunction[x, a3]]}}
$\endgroup$
1
$\begingroup$

Or:

sol /. Rule -> (Rule[#, myFunction @ #2] &)
(*
{{f[a1] -> myFunction[SomeComplicatedFunction[x, a1]]}, 
 {f[a2] -> myFunction[SomeComplicatedFunction[x, a2]]},
 {f[a3] -> myFunction[SomeComplicatedFunction[x, a3]]}}
*)

Safer:

Apply[Rule[#, myFunction@#2] &, sol, {2}]

Or:

# -> myFunction @ #2 & @@@ # & /@ sol

Or:

Dataset[Association /@ sol][All, Map@myFunction] // Normal // Normal
$\endgroup$

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.