4
$\begingroup$

is there an elegant way of replacing the RHS of a rule with the value of some function of it. Say I have {{a -> 1.2}, {a -> 2.3}} and I want to replace 1.2 with Sqrt[1.2] and 2.3 with Sqrt[2.3]? I know it can be done by pulling out the values, applying the function and building a new list of rules but this doesn't look very nice.

Thanks, Pete

$\endgroup$
  • 3
    $\begingroup$ MapAt[Sqrt, {{a -> 1.2}, {a -> 2.3}}, {;; , 1, 2}] $\endgroup$ – Kuba Nov 22 '14 at 13:25
4
$\begingroup$

You can use ReplaceAll.

{{a -> 1.2}, {a -> 2.3}} /. ({lhs_ -> rhs_} -> {lhs -> Sqrt[rhs]})
(* {{a -> 1.09545}, {a -> 1.51658}} *)

You can get fancier on the selection rule by changing or conditioning the pattern.

$\endgroup$
  • $\begingroup$ great, thank you so much. $\endgroup$ – Pete Nov 22 '14 at 13:22
  • 1
    $\begingroup$ I'd use :>. You never know what lives in Global` :) $\endgroup$ – Kuba Nov 22 '14 at 15:54
1
$\begingroup$
lst = {{a -> 1.2}, {a -> 2.3}} 
Normal /@ Sqrt /@ Association /@ lst

{{a -> 1.095445}, {a -> 1.516575}}

More generally,

Normal /@ Map[foo] /@ Association /@ lst

{{a -> foo[1.2]}, {a -> foo[2.3]}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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