# Construct a function like Coefficient

I'am trying to construct a function that will work like Coefficient as an exercise.

meuCoefficient1 // ClearAll
meuCoefficient1[_?NumericQ, x_Symbol] := 0
meuCoefficient1[(a_: 1)*x_Symbol + (b_: 0), x_Symbol] := a
meuCoefficient1[(a_: 1)*y_Symbol + (b_: 0), x_Symbol] := 0
meuCoefficient1[y_Symbol, x_Symbol] := 0
meuCoefficient1[y_Symbol + n_?NumericQ, x_Symbol] := 0


For the most cases my new function (meuCoefficient) works very well, except for the case when I have meuCoefficient[a*x + x,x]. In this case the solution has to be a+1, but my function is not defined for this case.

How should I extend my definition?

There are probably many ways to what you are asking. Here is one way, very likely not the best, but one which tries to maintain the style of your approach.

myCoeff // Clear
myCoeff[(a_.) y_Symbol, x_Symbol] /; y === x := a
myCoeff[poly_?PolynomialQ, x_Symbol] := Plus @@ Cases[poly, (a_.) x -> a]
myCoeff[_, x_Symbol] := 0


### Tests

myCoeff[x, x]


1

myCoeff[3 x + b, x]


3

myCoeff[a x + b, x]


a

myCoeff[3 x + x, x]


4

myCoeff[a x + x, x]


1 + a

myCoeff[a x + b x, x]


a + b

myCoeff[a x + a x, x]


2 a

• This is a good solution! But there is a way to do that without using Cases? @m_goldberg – Mateus Sep 18 '18 at 21:57
• @Mateus. Very likely there is, but why do you object to Cases? – m_goldberg Sep 18 '18 at 22:00
• Because I want to use less then possible the functions of Mathematica – Mateus Sep 18 '18 at 22:01
• @Mateus. You mean you want to do all the work in the righthand side of the function definition? But even so, you will have use functions such as Condition ( /; ) and PolynomialQ. IMO, imposing such a constraint will be more trouble than it's worth. – m_goldberg Sep 18 '18 at 22:10
• I can use conditions (/;) and PolynomialQ. I just want to avoid functions like Collect, Cases etc... – Mateus Sep 18 '18 at 22:13
ClearAll[meuCoefficient2 ]
meuCoefficient2[a_, x_Symbol] := Replace[a, _?(FreeQ[x] ) :> 0, {0, 1}] /. x -> 1

meuCoefficient2[#, x] & /@ {a + 5 + y, 5 + x, a + a x + x,  5 + y + a x + b x^2}


{0, 1, 1 + a, a + b}

Also

ClearAll[meuCoefficient3]
meuCoefficient3[a_, x_] /; FreeQ[a, x] := 0
meuCoefficient3[a_.  b_, x_] := a
meuCoefficient3[a_Plus, x_] := meuCoefficient3[#, x] & /@ a
meuCoefficient3[#, x] & /@ {a + 5 + y, 5 + x, a + a x + x, 5 + y + a x + b x^2}


{0, 1, 1 + a, a + b}