# Pattern matching for product of two terms fails if one factor is 1

I have a long set of replacement rules that I utilize to solve some longish integrals over trigonometric functions. Just look at this snippet (from this answer):

validQ[coeff___, arg_, v_] :=
FreeQ[{coeff}, v] && Exponent[arg, v] == 1;
testInt[v_, a_, b_] := {
coeff___*Cos[arg_] /; validQ[coeff, arg, v] :> coeff/Coefficient[arg, v]*Simplify[(First@Differences[Sin[arg] /. {{v -> a}, {v -> b}}]), Trig -> False],
(*failure rule*)
integrand_ :> Inactive[Integrate][integrand, {v, a, b}]
};


See, that e.g. 2*Cos[t] /. testInt[t, 0, \[Pi]/2] returns 2 as expected. However, I am struggling with terms that are like Cos[t]:

Cos[t] /. testInt[t, 0, \[Pi]/2]
(* Inactive[Integrate][Cos[t], {t, 0, \[Pi]/2}] *)


Same for 1*Cos[t]. However, applying the rules to 1.*Cos[t] yields 2.. In principle, I could just define an additional rule for Cos with the negative side-effect that I would have to be very cautious since this would also replace the Cos in terms where it may be wrong. How can I change the patterns so that ideally coeff___*Cos also accepts 1 as a coefficient?

Seems that I was just able to answer my own question. I came across Optional which seems to do exactly what I want. Changing the rule according to

validQ[coeff___, arg_, v_] := FreeQ[{coeff}, v]  && Exponent[arg, v] == 1;
testInt[v_, a_, b_] := {
(coeff___ : 1)*Cos[arg_] /; validQ[coeff, arg, v] :> coeff/Coefficient[arg, v]*Simplify[(First@Differences[Sin[arg] /. {{v -> a}, {v -> b}}]), Trig -> False],
(*failure rule*)
integrand_ :> Inactive[Integrate][integrand, {v, a, b}]
};


does the job. By this, it is possible to provide a default value (here 1) if coeff is absent in the expression. To test the rules:

Cos[t] /. testInt[t, a, b]
(* -Sin[a] + Sin[b] *)
2*Cos[t] /. testInt[t, a, b]
(* 2 (-Sin[a] + Sin[b]) *)
t*Cos[t] /. testInt[t, a, b]
(* Inactive[Integrate][t Cos[t], {t, a, b}] *)


Update

As pointed out by @Karsten in a comment, it is also possible to use coeff_. instead of coeff___:1.

• Using coeff_. should do the trick, too. Dec 4, 2015 at 12:42
• @Karsten7. True, also works! Thanks for this. Dec 4, 2015 at 12:44
• You are using the syntax for a custom default value, but as you specify it to be the built-in default value for multiplication you might as well use that. Dec 4, 2015 at 12:57