I am trying to set up a clever set of rules. Say, I am working symbolically with commutators comm
of matrices, where for instance
commRules={
comm[a_+b_,c_]:>comm[a,c]+comm[b,c],
comm[ac_?NumericQ * a_+bc_?NumericQ * b_,c_]:>ac*comm[a,c]+bc*comm[b,c],
};
Since those two rules are moreorless the same (up to the constants ac
and bc
), I am pretty sure one can combine them into one rule. I was thinking of using something like default arguments for functions, as for instance done in this question and answer - so maybe something along these lines: comm[ac:(_?NumericQ):1 *a_ + b_,c_]:>ac*comm[a,c]+comm[b,c]
. Of course, this does not work and ends up throwing an error.
Is it possible to combine the _?NumericQ
tests such that I do not have to hard-code each combination of where the constant factors may appear?
To be very clear, I would like to have a SINGLE rule commRule
that does e.g. do the follwing
comm[a+b,c]/.commRule
comm[2*a+b,c]/.commRule
comm[2*a+3*b,4*c]/.commRule
(* comm[a,c]+comm[b,c] *)
(* 2*comm[a,c]+comm[b,c] *)
(* 8*comm[a,c]+12*comm[b,c] *)
** Update **
I also unsuccessfully attempted to use BlankNullSequence
for this:
comm[a + b, c] /. {comm[a_ + fac2___?NumericQ*b_, c] :> comm[a, c] + fac2*comm[b, c]}
(* comm[a + b, c] *)
commRules={ comm[a_+b_,c_] :> comm[a,c]+comm[b,c], comm[ac_?NumericQ * a_,c_] :> ac*comm[a,c] };
$\endgroup$ReplaceRepeated
in order to split all commutators involving sums into the formcomm[a,c]
and then check for constants, right? This is my current approach actually, but I am curious if a one-liner exists. Can you please be a bit more specific about the subtle mistakes you're referring to? $\endgroup$