Skip to main content
1 of 5
einbandi
  • 4.1k
  • 2
  • 26
  • 43

How can I turn an expression to a function inside a Module

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 iside a Module. But it seems like there is a scoping problem:

Module[{x, expr}, expr = 2 x; Function[x, Evaluate[expr]]] (* Function[x$, 2 x$1713] *) 

Clearly, the x used in the first argument of Functionis 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?

einbandi
  • 4.1k
  • 2
  • 26
  • 43