I expected 3 from both of these
j = 2; new = {1, 1, 1, 1, 1}; new[[++j]] += 2; j
j = 2; new = {1, 1, 1, 1, 1}; new[[++j]] = 2; j
4
3
Why does the first one return 4?
That's really a nasty one. I don't think that it is supposed to work this way, but apparently,
new[[++j]] += 2
is equivalent to
new[[++j]] = new[[++j]] + 2
That's why ++j gets executed twice.
I am not sure, but maybe AddTo is implemented as follows:
SetAttributes[addto, HoldFirst];
addto[a_, b_] := a = a + b;
Since the first argument is held, new[[++j]] is evaluated twice under execution of addto[new[[++j]],2].
AddTo has that attribute. In principle, the held expression could be analyzed for occurences of Part and this behavior could be prevented by enforcing that the second arguments of Part get evaluated only once.
– Henrik Schumacher
Jul 21 '18 at 21:11
list, not the 3rd. – m_goldberg Jul 22 '18 at 03:17