Re: Increment and AddTo
- To: mathgroup at smc.vnet.net
- Subject: [mg64584] Re: [mg64551] Increment and AddTo
- From: Sseziwa Mukasa <mukasa at jeol.com>
- Date: Thu, 23 Feb 2006 00:34:22 -0500 (EST)
- References: <200602221058.FAA23452@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
On Feb 22, 2006, at 5:58 AM, dh wrote: > Hello, > can anybody explain the following behaviour: > $Version = 5.1 for Microsoft Windows (October 25, 2004) > > i = 0; > v = {1, 2, 3}; > v[[++i]] += 10; > v > i > > gives > {1,11,3} > 2 > > i has been incremented by 2! Using Trace the reason should be clear. Trace gives: Trace[v[[++i]] += 10;] {v[[++i]]+= 10;,{v[[++i]]+= 10,{{v,{1,2,3}},{++i,{i,0},{i=1,1}, 1},{1,2,3}[[1]],1},{{1+10,11}, v[[++i]]=11,11},11},Null} Since x+=dx is explicitly equivalent to x=x+dx it should be clear that x will be evaluated at least once before the assignment is done, that results in the expression x+dx evaluating to 11 in this case. Set[Part[_,_]] has special semantics though, the second argument of Part has to be evaluated before the assignment to know where the substitution must be made. Since Set has the attribute HoldFirst the second argument to Part is ++i not 1 so ++i gets evaluated again as you can see in the Trace where the expression v[[++i]]=11 gets evaluated. At that point ++i has already been evaluated once so obviously i will be incremented twice. > i++ is even more interesting: > i = 1; > v = {1, 2, 3}; > v[[i++]] += 10; > v > i > > gives: > {1,11,3} > 2 It's pretty much the same story, i++ gets evaluated twice, however the final value of i which I get is 3 not 2 which makes sense. > Further: > i = 0; > v = {1, 2, 3}; > ++v[[++i]] ; > v > i > > gives: > {1,2,3} > 2 > Again i has been incremented by 2, but v has not been touched at all. ++ is not equivalent to a Set expression so ++v[[++i]] does not share the special semantics that Set and Part do and the result of the expression does not modify the value of anything. Regards, Ssezi
- References:
- Increment and AddTo
- From: dh <dh@metrohm.ch>
- Increment and AddTo