Justin Talbot
2011-Sep-30 16:26 UTC
[Rd] Language definition question - order of argument side effects
I'm interested in the difference between these two intuitively equivalent sequences that produce different results (in R version 2.13.1 (2011-07-08) 32-bit). I think R's reference counting optimization is causing this difference in behavior.> a <- 1 > a+{a[1] <- 20}[1] 21> a <- 1 > a[1] <- 1 > a+{a[1] <- 20}[1] 40 Is one of these the "correct" answer, or is the order of side effects undefined in these statements? Section 4.3.3 of the R Language Definition just says that doing assignment in an argument to a function is "bad style", but doesn't say anything about evaluation order. In general, for primitive and internal functions, is a particular evaluation order for the arguments guaranteed? Thanks, Justin Talbot
Duncan Murdoch
2011-Sep-30 17:40 UTC
[Rd] Language definition question - order of argument side effects
On 30/09/2011 12:26 PM, Justin Talbot wrote:> I'm interested in the difference between these two intuitively > equivalent sequences that produce different results (in R version > 2.13.1 (2011-07-08) 32-bit). I think R's reference counting > optimization is causing this difference in behavior. > > > a<- 1 > > a+{a[1]<- 20} > [1] 21 > > > a<- 1 > > a[1]<- 1 > > a+{a[1]<- 20} > [1] 40 > > Is one of these the "correct" answer, or is the order of side effects > undefined in these statements? Section 4.3.3 of the R Language > Definition just says that doing assignment in an argument to a > function is "bad style", but doesn't say anything about evaluation > order. > > In general, for primitive and internal functions, is a particular > evaluation order for the arguments guaranteed?In general, evaluation order is undefined. I was surprised by the result, but I think you're right about the explanation. In particular:> a<- 1 > .Internal(inspect(a))@4a06440 14 REALSXP g0c1 [NAM(2)] (len=1, tl=0) 1> a[1]<- 1 > .Internal(inspect(a))@4a06300 14 REALSXP g0c1 [NAM(1)] (len=1, tl=0) 1 The only difference is in the "named" value. Duncan Murdoch