I have the following lists of rules:
{x -> 1, y -> 2}
{x -> 1, y -> 2, z -> 4}
{x -> 1, y -> 2, z -> 2}
For each list of rules, I would like to add the rule z -> 3
or replace any rule whose lhs is z
with z -> 3
.
I am able to get this to work for specific rules, for example z -> 4
AddReplaceRule[rules_List] :=
Module[{newRules},
If [MemberQ[rules, z -> 4],
newRules = DeleteCases[rules, z -> 4];
,
newRules = rules;
];
Append[newRules, z -> 3]
]
Results
Note I am expecting to see {x -> 1, y -> 2, z -> 3}
for all three cases, but that is not the case, since I need to generalize z -> 4
in AddReplaceRule.
In[]:= AddReplaceRule[{x -> 1, y -> 2}]
Out[]= {x -> 1, y -> 2, z -> 3}
In[]:= AddReplaceRule[{x -> 1, y -> 2, z -> 4}]
Out[]= {x -> 1, y -> 2, z -> 3}
In[]:= AddReplaceRule[{x -> 1, y -> 2, z -> 2}]
Out[]= {x -> 1, y -> 2, z -> 2, z -> 3}
Prepend
your new rule to the list. You will then have rules with the same l.h.s., true, but the new rule will always apply first, just because of the way rule application works. Unless these operations are so frequent that you grow truly huge list of rules, this should work fine. And if you do, you can periodically useDispatch
on these rules. You can even set up a wrapper which would do that automatically, which, however, is slightly more complex and may be destroying the purpose. $\endgroup$