Here is slight modification that generalizes Jens's.
eval[sympoly_, coeffQ_:False] := Head@sympoly /. s_?
(MemberQ[
Variables[Head@sympoly] /. v_?coeffQ -> Sequence[]
, #] &
) :> s[Level[sympoly, 1] /. List -> Sequence]
The pattern sympoly_
holds an expression of the form (f^2g + fg + g)[x]
, as in the question. Jen's evaluation rule is applied to the Head
of sympoly
, while the evaluation point is extracted using Level
and the r.h.s. of Jen's rule s[x]
modifed to s[Level[sympoly, 1] /. List -> Sequence]
.
Which expressions in sympoly
are to be considered variables is checked with a Boolean test (MemberQ
). First, all possible variables are obtained using Variables
. Then, they are filtered with a rule to exclude coefficients (using the ad-hoc test function coeffQ
). By default numerical symbols are coefficients as they are not recognized as variables by Variables
. The variables of sympoly are the output of
Variables[Head@sympoly] /. v_?coeffQ -> Sequence[]
Here's an example
(3 f^2 g + f g + g)[x] // eval
g[x] + f[x] g[x] + 3 f[x]^2 g[x]
Here coefficients are h[i], h[j], h[k]
(any symbol with head h
):
eval[(h[i] f^2 g + h[j] f g + h[k] g)[x], Head[#] == h &]
f[x]^2 g[x] h[i] + f[x] g[x] h[j] + g[x] h[k]
The function eval
works also on more general symbols
(3 f[1]^2 f[2] + ff g[f[h]])[x, y, z] // eval
3 f[1][x, y, z]^2 f[2][x, y, z] + ff[x, y, z] g[f[h]][x, y, z]