4
$\begingroup$

I'm trying to create a list of functions by replacing variables in a template. I tried this:

In[1]:= Table[Function[{x,y}, (x + y) v], {v, {x,y}}]
Out[1]= {Function[{x, y}, (x + y) v], Function[{x, y}, (x + y) v]}

But these functions have v in them. I was expecting to get:

{Function[{x, y}, (x + y) x], Function[{x, y}, (x + y) y]}

I thought this would work because I can do something similar with Solve:

In[2]:= Table[Solve[(x + y) v == 1 && x == y], {v, {x, y}}]
Out[2]= {{{x -> -(1/Sqrt[2]), y -> -(1/Sqrt[2])}, …

This is equivalent to:

In[3]:= {Solve[(x + y) x == 1 && x == y], Solve[(x + y) y == 1 && x == y]}
Out[3]= {{{x -> -(1/Sqrt[2]), y -> -(1/Sqrt[2])}, …

It seems like it's replacing v with x/y in the Solve example, but not the Function example. Substituting Function[{x,y}, (x + y) Evaluate[v]] for Function[{x,y}, (x + y) v] doesn't help. What's going on here? How can I generate a list of similar functions?

$\endgroup$
4
  • 2
    $\begingroup$ Function[{x, y}, (x + y) #] & /@ {x, y} $\endgroup$
    – Bob Hanlon
    Commented Oct 14, 2020 at 22:40
  • 2
    $\begingroup$ This is an effect of Function's HoldAll attribute. Use /. or something like what Bob Hanlon is suggesting to work around it. $\endgroup$
    – eyorble
    Commented Oct 14, 2020 at 22:41
  • $\begingroup$ @eyorble If that's the case, then why doesn't Evaluate[v] help? It seems like it should, according to reference.wolfram.com/language/tutorial/… $\endgroup$
    – ppm
    Commented Oct 15, 2020 at 18:35
  • 2
    $\begingroup$ @ppm: Evaluate evaluates before Table, so Table's internal expression is still a function with HoldAll. $\endgroup$
    – eyorble
    Commented Oct 15, 2020 at 18:59

1 Answer 1

1
$\begingroup$

The question is similar to how to construct a series of pure functions.

Function /@ Table[(Slot[1] + Slot[2]) v, {v, {Slot[1], Slot[2]}}]

Some codes similar with @BobHanlon in the comment is

Outer[Function[{x, y}, (x + y) #] &, {x, y}]
$\endgroup$
1
  • $\begingroup$ Is there any reason to use Outer instead of Map? $\endgroup$
    – ppm
    Commented Oct 16, 2020 at 21:29

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.