4
$\begingroup$

I'm trying to create a function that takes in input a function written as string and the return it applying a ToExpression and an Evaluate (Code below). The goal of this function is to transform the function, written inside a string, into a Mathematica expr.

FunctionFromStr[strF_] :=
        Module[{expF,f},
            expF = ToExpression[strF, TraditionalForm]
            f[x_] = Evaluate[expF]
            Return[f]
]

This code doesn't work, if I try it I get

g = FunctionFromString["x+1"]
g[1]

FunctionFromString["x+1"]

What can I do to solve this? Thanks

$\endgroup$

1 Answer 1

4
$\begingroup$

Welcome to the community.
With little generalization (be applied to any variable name), Here is how you can achieve your goal:

Since Function has HoldAll attribute, you have to evaluate its arguments first:

ClearAll[FunctionFromString];

FunctionFromString[str_, vars_] := 
 Function[Evaluate[ToExpression[Characters[vars]]], 
  Evaluate[ToExpression[str]]]

Result

g = FunctionFromString["x+1", "x"];

g[1]
(* Out: 2 *)

g /@ Range[5]
(* Out: {2, 3, 4, 5, 6} *)

It works with multiple variables:

g2 = FunctionFromString["x+y", "xy"];

g2[3, 5]
(* Out: 8 *)

I should also point out that using ToExpression should come with security considerations if you want to apply it to inputs you don't have control over.

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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