Message Boards Message Boards

2
|
10093 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Creating a function from an expression containing variables

Posted 7 years ago

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 &
POSTED BY: Ta'a Nwa Dombou
2 Replies

A variation on the theme:

exprToFunction[expr_, vars_] := 
 Function[Evaluate[expr /. Thread[vars -> Array[Slot, Length[vars]]]]]

If you didn't insist on pure functions, you could get away with

exprToFunction[expr_, vars_] := Function[vars, expr]
POSTED BY: Gianluca Gorni

You can avoid ToExpression and ToString by :

exprToFunction[expr, vars] := Function @ expr /. MapIndexed[#1 -> Slot @@ #2 &, vars]

POSTED BY: Rolf Mertig
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract