I am trying to match monomials of the type x^a y^b, where a, b can be 0, 1, 2, ...
So far I have been able to come up with the following rule, using Optional
patterns:
Table[x^i y^j, {i, -2, 2}, {j, -2, 2}] //
Replace[#,
expr : (a : (x^i_. /; i >= 0) : 1) (b : (y^j_. /; j >= 0) : 1) ->
Framed[expr], {2}] & // MatrixForm
Question:
The pattern also feels a little clunky. Is there a more idiomatic way to express it? Do I really need to name "a" and "b" in optional "complex" patterns, when I don't care about them being named?
Also, why isn't "1" being matched? I would have thought that when "a" and "b" are take their default values, then
Times[1, 1]
would simplify to 1.
I tried to use alternatives such as expr : (x^i_. /; i >= 0 | 1) (y^j_. /; j >= 0 | 1)
, but this didn't work, although I didn't quite understand why...
Optional[x^Optional[_?NonNegative]] Optional[y^Optional[_?NonNegative]]
$\endgroup$Optional[_?NumericQ]
you can also match the1
and monomials with numeric prefactors $\endgroup$Replace[#, expr_ /; PolynomialQ[expr, {x, y}] && ! NumberQ[expr] :> Framed[expr], {2}]
. $\endgroup$Length@MonomialList[expr, {x, y}] == 1
. $\endgroup$