The problem you encountered is due to the evaluation algorithm used by
Mathematica. In the documentation of SetDelayed
is this statement
SetDelayed has attribute HoldAll, rather than HoldFirst.
What this means is that you do want the RHS to be evaluated in your case.
As usual, you can force this by using f[x_]:=Evaluate[function]
or else by using
the alternate Set
function with f[x_]=function
. In the usual situation such
as f[x_]:=x^2
we do want to RHS to be held unevaluated until the function
is called. In your case function
is a symbol which, only when evaluated, becomes
the x^2
that you want in the function definition.
The decision to use =
instead of :=
is a matter of preference and
convenience but it is context dependent.
For example, in the case of function=x^2
you have to ensure that the symbol,
in this case x
, does not have a value, otherwise function
will use that
value which is not what you want. You have to remember to use
ClearAll[x]
or x=.
before using x
to remove any value that x
has.
If you use the standard f[x_]:=x^2
then this is automatically taken care of.
You will run into the same problem if you use f[x_]=x^2
and forget to use :=
instead because if x
has a value then that value
will be used in the function
definition and that is almost certainly
not what you want.