You may already have discovered that something like g[#]&
doesn't work - this is because Function
has the HoldAll
Attribute, so its argument (g[#]
in this case) doesn't get evaluated. The solution is to force g[#]
to evaluate. Rasher showed what one way to do that, by using Evaluate
, whose specific purpose is to force evaluation of arguments that would normally be held unevaluated.
Another way is to create the Function
with a dummy body, then replace that body with the result of evaluating g[#]
. Like this:
func = body & /. body -> g[#]
(* Piecewise[{{0, #1 < 8.}, {2.5, 8. <= #1 < 10}}, 0] & *)
func[9]
(* 2.5 *)
As is often the case in Mathematica, there are many ways to accomplish the same thing. Here are a few more.
Use With
(a lexical scoping construct) to inject the evaluated expression into the Function
:
func = With[{body = g[#]}, body &]
Wrap the expression to be evaluated in a Head which does not hold its arguments (such as List
) and use Apply
to replace that head with Function
:
func = Function @@ {g[#]}
Use the DownValues
of g
as a replacement rule directly:
func = g[#] & /. DownValues[g]
Use Block
(a dynamic scoping construct) to evaluate g[#]&
in an environment where Function
temporarily has no meaning and no special Attributes:
func = Block[{Function}, g[#] &]
ruleToFunction[rule_]:=...
that returns a pure function corresponding to whatever rule it was given. So,ruleToFunction[f]
would returnFunction[# Sin[#^2]]
, using my above example. $\endgroup$