1

Could someone please explain the difference between these methods, and possibly a nicer way to get the first result? (This is a toy example and in my real program I'd like to use Do rather than Table or similar as there are imperative and global things going on).

Method 1 (Desired result):

In[5]:= fsum[f_]=Total@Through[f@#]&;
fs={};
Do[
AppendTo[fs,#^n1&/.n1->n];
,{n,0,10}]
fsum[fs][a]

Out[8]= 1+a+a^2+a^3+a^4+a^5+a^6+a^7+a^8+a^9+a^10

Method 2:

In[9]:= fsum[f_]=Total@Through[f@#]&;
fs={};
Do[
AppendTo[fs,#^n&];
,{n,0,10}]
fsum[fs][a]
Out[12]= 11 a^n

Method 3:

In[13]:= fsum[f_]=Total@Through[f@#]&;
fs={};
Do[
n1=n;
AppendTo[fs,#^n1&];
,{n,0,10}]
fsum[fs][a]
Out[16]= 11 a^10A

1 Answers1

0

I'd use

fs = Reap[Do[With[{n = n}, Sow[#^n &]], {n, 0, 10}]][[2, 1]]
{#1^0 &, #1^1 &, #1^2 &, #1^3 &, #1^4 &, #1^5 &, #1^6 &, #1^7 &, #1^8 &, #1^9 &, #1^10 &}

Your methods 2 & 3 don't work because Function has the attribute HoldAll and therefore

m = 2;
#^m &
#1^m &

With can be used "to insert values into held expressions."

Karsten7
  • 27,448
  • 5
  • 73
  • 134