Using global variables the following turns an "expression" into a Function:
expr = 2 x; Function[x, Evaluate[expr]] Of course this doesn't work if for some reason a value is assigned to x. Thus, I want to turn expr into a Function isideinside a Module. But it seems like there is a scoping problem:
Module[{x, expr}, expr = 2 x; Function[x, Evaluate[expr]]]Evaluate[expr]] ] (* Function[x$, 2 x$1713] *) Clearly, the x used in the first argument of Functionis is not the same as the x in the second. I played around with Evaluate and even with Replace and Slot, also trying to create a function with an anonymous variable, but didn't succeed. The only way that I managed to get the right result is this one involving strings:
Module[{x, expr}, expr = 2 x; "(" <> StringReplace[ToString@expr, ToString@x -> "#1"] <> ")&" // ToExpression ] Is there a simpler, more straight-forward way to achieve this, without ever using any global variables?