Stumbled on Local variables when defining function in Mathematica in math.SE and decided to ask it here. Apologies if it is a duplicate - the only really relevant question with a detailed answer I could find here is How to avoid nested With[]? but I find it sort of too technical somehow, and not really the same in essence.
Briefly, things like f[n_]:=Sum[Binomial[n,k],{k,0,n}] are very dangerous since you never know when you will use symbolic k: say, f[k-1] evaluates to 0. This was actually a big surprise to me: by some reason I thought that summation variables and the dummy variables in constructs like Table are automatically localized!
As discussed in answers there, it is not entirely clear what to use here: Module is completely OK but would share variables across stack frames. Block does not solve the problem. There were also suggestions to use Unique or Formal symbols.
What is the optimal solution? Is there an option to automatically localize dummy variables somehow?
Tablebut it applies toSumas well. Short answer: useModule. – WReach May 04 '20 at 17:48Modulewould share variables across stack frames. Is this correct? – მამუკა ჯიბლაძე May 04 '20 at 19:21Uniquewould just replicate whatModuledoes internally.Sumuses an implicitBlockalready, so adding another does not help. Formal variables run the risk of name collisions. The unique temporary symbols generated byModulesimulate local variables well enough to be indistinguishable from them for most practical purposes. – WReach May 04 '20 at 21:31f[n_] := Evaluate@Sum[Binomial[n, k], {k, 0, n}]– Bob Hanlon May 05 '20 at 05:15