# Defining a function of a variable through another intermediate variable

The following is a really simplified version of what I'm trying to do. I have a variable fn defined in terms some other variable x. I then want to define a function of x through the variable fn.

fn = x^2;
f[x_] := fn
f[2]


However, Mathematica doesn't like it. For f[2] it just spits out $$x^2$$. How can I make this work? (In my complicated case I really don't want to define a function fn[x_]:=x^2 and then define f[x_]:=fn[x_])

Edit: It has been suggested to use Evaluate@fn. Which indeed works. However, let me propose a different example that doesn't work:

fn = x^2 a^2;
f[x_] := NIntegrate[Evaluate@fn, {a, -1, 1}]
f[2]


(and similarly if I put Evaluate@NIntegrate instead)

• try f[x_] := Evaluate@fn it is because you used delayed assignment. If you used f[x_] = fn then it would have worked. But delayed is better in general. You just need to know the difference between = and := in Mathematica. These have different semantics. ps. this type of question has been asked before few times,. I am sure it is somewhere in what-are-the-most-common-pitfalls-awaiting-new-users/ Commented Dec 23, 2023 at 22:03
• Thank you @Nasser, see my edit in the question above. Commented Dec 23, 2023 at 22:19
• The only real answer is: you shouldn't be doing this in the first place. Mathematica doesn't like it for a reason. In any case you may want to look into Block. Commented Dec 23, 2023 at 22:48

(* make a legit function *)

This forces the x to get replaced first when you call fInt.