10

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?

user366202
  • 451
  • 2
  • 8

4 Answers4

11
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]]}} *)
Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198
9

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

kglr
  • 394,356
  • 18
  • 477
  • 896
1

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]]}}
kglr
  • 394,356
  • 18
  • 477
  • 896
1

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
Michael E2
  • 235,386
  • 17
  • 334
  • 747