Skip to main content
Addressed scoping problem
Source Link
Jens
  • 98.4k
  • 7
  • 217
  • 541

To inject expressions into a function, I use one of the following:

f1 = With[{expr = 2 x}, Function @@ {x, expr}]; f1[5] (* ==> 10 *) f2 = Function[x, body] /. body -> (2 x); f2[5] (* ==> 10 *) 

Modification in light of the comments

The first approach works fine inside Module, the second doesn't, as mentioned by Szabolcs. To fix this, one can do a more comprehensive replacement like this:

Module[{x}, f3 = Function[x1, body] /. {x1 -> x, body -> (2 x)}; ] f3[3] (* ==> 6 *) 

To inject expressions into a function, I use one of the following:

f1 = With[{expr = 2 x}, Function @@ {x, expr}]; f1[5] (* ==> 10 *) f2 = Function[x, body] /. body -> (2 x); f2[5] (* ==> 10 *) 

To inject expressions into a function, I use one of the following:

f1 = With[{expr = 2 x}, Function @@ {x, expr}]; f1[5] (* ==> 10 *) f2 = Function[x, body] /. body -> (2 x); f2[5] (* ==> 10 *) 

Modification in light of the comments

The first approach works fine inside Module, the second doesn't, as mentioned by Szabolcs. To fix this, one can do a more comprehensive replacement like this:

Module[{x}, f3 = Function[x1, body] /. {x1 -> x, body -> (2 x)}; ] f3[3] (* ==> 6 *) 
Source Link
Jens
  • 98.4k
  • 7
  • 217
  • 541

To inject expressions into a function, I use one of the following:

f1 = With[{expr = 2 x}, Function @@ {x, expr}]; f1[5] (* ==> 10 *) f2 = Function[x, body] /. body -> (2 x); f2[5] (* ==> 10 *)