A package I'm working on uses rule solutions (like the output of Solve
) as inputs to functions. I'd like to be able to easily manipulate these rule solutions by overloading Plus
. Here are some examples of the behavior what I want:
{x -> 1} + {x -> 2}
(* {x -> 3} *)
{x -> 1} + {y -> 2}
(* {x -> 1, y -> 2} *)
{x -> 1, y -> 2} + {x -> 2}
(* {x -> 3, y -> 2} *)
Is there an easy way to implement this? Right now I'm getting some of this functionality using a function called Tweak
to tweak one coordinate:
Tweak[point_,var_Symbol,h_]:=Append[Select[point,#[[1]]=!=var&],var->((var/.point)+h)];
but would rather have the syntax above.
Answer
So both points i want to address are already pointed out in the comments.
First of all, overloading Plus is a really bad idea. Especially if you realize, that Plus already handles your first two cases in its own way.
So we really should be keeping it by implementing our own function and using it in an operator-form.
So like pointed out, we'll use Merge
:
rt[p__]:=Normal@Merge[Flatten@List[p],Total]
(name it whatever you like)
So you can call it normally with multiple arguments and nested lists
rt[{{x->1},{{y->2}}},{x->2},{a->5}]
{x->3,y->2,a->5}
But i think, you like it more that way:
{x->1}~rt~{x->2}
{x->1}~rt~{y->2}~rt~{x->1,y->2}~rt~{x->2}
{x->3}
{x->4,y->4}
Not as clean as a simple Plus, but it works.
Comments
Post a Comment