The problem isn't with Optional
but with the fact that Plus
will evaluate pattern sequences as in _ + _
to get unpleasant results like 2 _
. In your pattern, you can prevent this by simply wrapping everything in HoldPattern
:
Clear[intPolyQ]
intPolyQ[HoldPattern[
Optional[_Integer] +
Plus[Optional[_Integer] x_Symbol^Optional[_Integer] ...]], x_] :=
True;
intPolyQ[___] := False;
With this, the function seems to work fine:
intPolyQ[#, x] & /@ {x, 2 x, 2 x + 1, 2 x^2 + 3 x, 2 x^2 + 3 x + 1}
(* ==> {True, True, True, True, True} *)
Of course there is also an easier way to test for integer polynomials - let's call the polynomial poly
, then you could just do
And @@ IntegerQ /@ CoefficientList[poly]