Evaluating the following piece of code, returns-as expected-3:
g[a_] = a;
With[{a = 1},
2 + g[a]
]
Why does the following snippet produce the counter-intuitive result 2+a?
f = a;
With[{a = 1},
2 + f
]
Is the later case an example of a use case where using Block is preferable?
edit
The direct motivation for this question, comes from the solution I proposed to this question, here.
There, I needed a way to initialize numerically matrix H.
In that case, I had to revert to using ReplaceAll because a construct like With proved a bad choice; alternatively, Block might have been a better/more straightforward decision-hence the second part of this question.
An indirect motivation comes from this question, where it seems that With behaves in an unexpected way; that consideration prompted the first part of this question.
Having said all that, I hope that it is now fairly obvious that the question is more about practical considerations rather than theoretical/syntactical issues; I am interested in how a seasoned Mathematica programmer would tackle the issues codified in the toy example presented in the body of the question and -hopefully- exemplified in this postscript.
Blockwill give you the answer you were expecting, and also explains whyWithdoesn't. If you believe it should be reopened (the purpose of which is to allow posting answers), it is better to give a convincing explanation than just cast a vote. – Szabolcs Jan 21 '18 at 16:51