3
$\begingroup$

I know how to create a function from concrete expression like

Function[{x, y}, x^2 + y^2]

But what if I have a list of expressions list1 and I know the set of variables which can occur in this list. I want to map all expressions of list1 to curresponding functions from these variables. Like

{x^2 + y^2, z^2, x, y}

should be mapped to

{
  Function[{x,y,z}, x^2 + y^2], 
  Function[{x,y,z}, z^2], 
  Function[{x,y,z}, x], 
  Function[{x,y,z}, y]
}

I've tried

Function[{x,y,z}, #] &/@ list1

but this doesn't work. Can someone help me with solution?

$\endgroup$
2
  • $\begingroup$ Something like g = Function[{x, y, z}, #] & /@ l1; g[[1]][a, b, c]? $\endgroup$ Commented May 18, 2014 at 13:21
  • $\begingroup$ Or this way?g = Function[{x, y, z}, #] &@l1; g[a, b, c][[1]] $\endgroup$ Commented May 18, 2014 at 13:22

1 Answer 1

2
$\begingroup$

One way to do it is:

exprs = {x^2 + y^2, z^2, x, y};
Replace[Function[{x, y, z}, body], {Rule[body, #]} & /@ exprs, {-1}]
{
   Function[{x, y, z}, x^2 + y^2], 
   Function[{x, y, z}, z^2], 
   Function[{x, y, z}, x], 
   Function[{x, y, z}, y]
}
$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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