delayed icon indicating copy to clipboard operation
delayed copied to clipboard

Warn users about nonstandard evaluation

Open nhejazi opened this issue 7 years ago • 2 comments

Apparently, delayed appears to interact in an odd way with repeated calls to functions that generate random variates. In particular, the expression replicate(3, rnorm(100)) will produce a matrix with 3 columns, each corresponding to 100 random draws from a N(0, 1) distribution. This is not the case when one invokes delayed(replicate(3, rnorm(100)))$compute(), which returns a matrix of similar form but with each of the 3 columns being exactly the same.

nhejazi avatar Sep 28 '17 18:09 nhejazi

This is actually an issue with the interaction between delayed and replicate. Both delayed and replicate use nonstandard evaluation (NSE), and their usage conflicts.

delayed evaluates all function arguments before calling a function to determine if they themselves are delayed, and then passes the results of those evaluations to the function call. Here, that means evaluating rnorm(100) and calling replicate on its result. In contrast, replicate captures the expression passed to its second argument unevaluated, and then repeatedly evaluates it.

You could generate something equivalent to replicate(3, rnorm(100)) with delayed(sapply(1:3,function(x)rnorm(10)))$compute(), because sapply doesn't use NSE.

It seems worth warning the user to be careful with the combination of delayed and other functions that use NSE. Do you think the vignette is a good place for this? There's a good discussion on related issues here: http://adv-r.had.co.nz/Computing-on-the-language.html#nse-downsides

jeremyrcoyle avatar Sep 28 '17 19:09 jeremyrcoyle

Ok, good to know. Yes, I think it's worth adding an "Advanced" section to the vignette that warns users about these sorts of situations, perhaps with a reference to Hadley's book.

nhejazi avatar Sep 28 '17 19:09 nhejazi