1
$\begingroup$

Sometimes Table[ ] leaves the looping variable in the output, instead of replacing it by the values. For example

In[255]:= Table[{v, #[v] &, # /. x -> v &}, {v, {0, 1}}]

gives

Out[255]= {{0, #1[v] &, #1 /. x -> v &}, {1, #1[v] &, #1 /. x -> v &}},

instead of the desired

Out[255]= {{0, #1[0] &, #1 /. x -> 0 &}, {1, #1[1] &, #1 /. x -> 1 &}}.

Is there a way to force Table[ , {v, {0,1}}] to properly replace v by the values 0 and 1?? Can anyone explain this bizarre behavior?

$\endgroup$
  • $\begingroup$ You could use a dummy variable u and then replace, as in Table[{u, #[u] &, # /. x -> u &} /. u -> v, {v, {0, 1}}]. Or not use Table: {v, #[v] &, # /. x -> v &} /. Array[{v -> #} &, 2, 0]. $\endgroup$ – aardvark2012 Nov 2 '17 at 2:57
  • $\begingroup$ Can you explain what you are trying to do? What is the goal of this construction? $\endgroup$ – bill s Nov 2 '17 at 3:02
  • $\begingroup$ What is #[v] & supposed to give? Can you give what is the expected output of Table[{v, #[v] &, # /. x -> v &}, {v, {0, 1}}]? It is not clear what you want to generate. $\endgroup$ – Nasser Nov 2 '17 at 3:02
  • $\begingroup$ Nasser: #[1]& is a pure function which sends the input f to the output f[1]. Bill: I was using such functions to as inputs to a somewhat abstract constrained optimization routine I wrote. In particular, I wanted to use the above function tell the optimizer to optimize only over functions f which evaluated to certain values in certain places. I found a work-around, but it very much bothers me when basic functions such as Table[ ] do unexpected things, so I want to know what is going on here. $\endgroup$ – J Tyson Nov 2 '17 at 3:05
2
$\begingroup$
Table[With[{v = v}, {v, #[v] &, # /. x -> v &}], {v, {0, 1}}]

{{0, #1[0] &, #1 /. x -> 0 &}, {1, #1[1] &, #1 /. x -> 1 &}}

$\endgroup$
  • $\begingroup$ Thanks, exactly what I needed. $\endgroup$ – J Tyson Nov 2 '17 at 3:16
  • 1
    $\begingroup$ @JTyson, my pleasure. Thank you for the accept. $\endgroup$ – kglr Nov 2 '17 at 3:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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