This is due to the special behavior of SetDelayed
(:=
) with regards to the first argument (see e.g. this question): The arguments of the l.h.s. are evaluated by SetDelayed
, which causes the error you are seeing - after all, SeriesData[_, _, coeff_, _, _, _]
is not a valid SeriesData
construct. This is what HoldPattern
is designed for: It prevents evaluation of its argument (like Hold
), but is invisible to the pattern matcher. The solution is therefore simply:
(* prevent the l.h.s. from being evaluated *)
HoldPattern@getCoeff[SeriesData[_, _, coeff_, _, _, _]] := coeff[[2]]
getCoeff@Series[E^(π x), {x, 0, 3}]
(* π *)
(* prevent only evaluation of the first argument (equivalent in this case) *)
getCoeff[HoldPattern@SeriesData[_, _, coeff_, _, _, _]] := coeff[[2]]
getCoeff@Series[E^(π x), {x, 0, 3}]
(* π *)
In this caseAs noted in the comments, the original version works perfectly fine ignoring the error would be of no consequencemessage: If you look at ?getCoeff
, you'll see that the definition that was actually made is the same with and without HoldPattern
. If you evaluate SeriesData[_, _, coeff_, _, _, _]
on its own, you will see that you get the error message, and then the input will be returned (which happens for many Mathematica functions) - if you would have gotten something else back, the definition would not work.