0
$\begingroup$

With a very high frequency I find myself working with giant and hard to alter expressions in a situation where it would be convenient to do something like

function = x^2;

f[x_]:= function;

which obviously doesn't work. I have also tried using InputForm[function] which does not work either.

How can I do something like this?

$\endgroup$

2 Answers 2

1
$\begingroup$
ClearAll[f,x]
function = x^2;
f[x_] = function;
DownValues[f]  (* {HoldPattern[f[x_]] :> x^2} *)


ClearAll[f]
f[x_] := x^2;
DownValues[f]  (* {HoldPattern[f[x_]] :> x^2} *)
$\endgroup$
2
$\begingroup$

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.

$\endgroup$
2
  • $\begingroup$ Thank you!!! Now, what would be the threats of using Set instead of SetDelayed while routinely defining functions? $\endgroup$
    – GaloisFan
    Commented Apr 1, 2021 at 20:40
  • $\begingroup$ @GaloisFan - If the symbols used in the definition of the function have previously been given values, using Set will not do what you expect. Evaluate Clear["Global`*"]; x = 2; f[x_] = x^2; f[3] $\endgroup$
    – Bob Hanlon
    Commented Apr 2, 2021 at 0:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.