String to function and vice versa

How can a string like “x^3 + 6x^2 + 6x” be turned into a function

p(x) = x^3 + 6*x^2 + 6*x

and conversely, given the function p, how to extract the body of the function as a string?

julia> eval(Meta.parse("p(x) = x^3 + 6*x^2 + 6*x"))
p (generic function with 1 method)

julia> p(2)

julia> p(3)
1 Like

Make sure you are not passing functions as strings. If you want a caller to pass a function like x^3 + 6x^2 + 6x, have them pass an anonymous functions like x -> x^3 + 6x^2 + 6x, not a string that you need to parse and eval.


The situation is the reverse: I am the caller, and I get a structure returned in which the polynomials are given in this form. I have to convert them to functions. So I do not see a better solution then jling’s.

Why are the polynomials in that form? Can’t they just be returned as an array of coefficients for example?