Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

This question already has an answer here:

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
share|improve this question

marked as duplicate by Michael E2, Pickett, eldo, Simon Woods, RunnyKine Aug 28 at 16:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
I think this question can be closed as a duplicate of: (7756) -- please review that question and tell me if you disagree. –  Mr.Wizard Aug 28 at 10:54

1 Answer 1

up vote 1 down vote accepted

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."

share|improve this answer

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