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.

=================

What version of Mathematica are you using? If it’s pretty modern (10.0+, is where I would start guessing), Associations are a new feature that put you really close to what you’re trying to build there using Lists of Rules. Check out Association and Merge.

– sblom

yesterday

Overloading fundamental functions like Plus is a seriously bad idea. All kinds of (un-)foreseeable consequences. I would use Associations as recommended above or use replacement rules, something like {x -> 1} + {x -> 2} /. Rule[x_, y_] + Rule[x_, z_] :> Rule[x, y + z].

– march

yesterday

@sblom You’ve convinced me that overloading Plus is a bad idea (especially if it’s in a package I unleash on the unsuspecting :). Reading through some other posts, I see there are some operators without built-in meanings, such as CirclePlus. Do you think that’s OK to define in such a context?

– Chris K

yesterday

@sblom I’m on 11, but would like to be compatible with a wider range of versions.

– Chris K

yesterday

=================

2 Answers

2

=================

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.

It’s usually not a good idea to overload symbols that may have applications deep within the system, but if you insist, this will do what you’re asking for:

Unprotect[Plus]

Plus[a__Rule, b__Rule] := Normal[Merge[{a, b}, Total]]

Protect[Plus]

I’ll avoid changing Plus – just a note that I had to add some braces to this: plus[{a__Rule}, {b__Rule}] := Normal[Merge[{a, b}, Total]] but otherwise works great

– Chris K

yesterday