Imagine that you have an expression of the form $ x + y^2$ that you want to turn into a pure function. How do you do it in MATHEMATICA? I encountered this problem while developing an application. I search the web and found that somebody had the same problem some years ago at this location http://mathematica.stackexchange.com/questions/31985/turn-expression-into-function. I survey the answers there but they are not satisfactory for several reasons. Below, I provide a surprising one-liner that solve the problem.
exprToFunction[expr_, vars_] := ToExpression[ToString[FullForm[expr] /. MapIndexed[#1 -> Slot@@#2 &, vars]] <> "&" ] ;
The main idea is to build the string string form of the sought pure function. Then turn it into a pure function using the built-in function ${\tt ToExpression}$.
We can now perform few tests to ensure that the function works as expected.
expr1 = 3 + 2 *Cos[t] + 3 *Cos[2 *t] + 5 *Cos[3*t] + 7 *Cos[4*t] + 9 *Sin[t] + 4 *Sin[3*t] + 5 *Sin[4*t];
f = exprToFunction[expression, {t}]
After compiling the above code, you should obtain something like this
3 + 2 Cos[#1] + 3 Cos[2 #1] + 5 Cos[3 #1] + 7 Cos[4 #1] + 9 Sin[#1] + 4 Sin[3 #1] + 5 Sin[4 #1] &
Now let's us try a situation where there are several variables.
expr2 = exprToFunction[x + y^2 + Sin[z], {x, y, z}]
The output after compiling is as expected
Sin[#3] + #1 + #2^2 &