I am learning mathematica, and I am stuck at the point where I want to pass an unevaluated expression (a polynomial) to a function and work with that expression / polynomial inside the function. For simplification reason, assume the following setup, which should give me the coefficients of the polynomial:
SetAttributes[myCoef, HoldAll]
myCoef[exp_] := CoefficientList[exp, Variables[exp]]
This works fine for the following call:
p = myCoef[5*x^3 + 4*x^2 + 3]
(* Returns {3, 0, 4, 5} *)
The problem is, when I set x
on the global scope:
x = 5
p = myCoef[5*x^3 + 4*x^2 + 3]
(* Returns 728 *)
How can I prevent the evaluation of 5*x^3 + 4*x^2 + 3
to 728
?
What would I have to change in myCoef
to make it work, even if x
is defined globally?
\[FormalX]
(and similar) or maybe use pure functions as inmyCoef[5*#^3 + 4*#^2 + 3]
. $\endgroup$SetAttributes[newPoly, HoldAll]
should probably havemyCoef
rather thannewPoly
? $\endgroup$myCoef
, I edit it. $\endgroup${0,1}
which I just glossed over as being the right answer, but obviously it's a) wrong, b) in the correct form for an answer fromCoefficientList
. Obviously my suggestion wasn't correct, but I'm curious why it's giving two different answers. What version are you using? $\endgroup${0,1}
. Somehow I'd replacedHoldForm
with something that looked the same but contained non-printing characters -- its FullForm wasHoldFor\:200c\:200bm
. Weird, but explains why what looked likeHoldForm
showed up in blue rather than black. $\endgroup$