Understanding lazy grades in R

I am trying to understand how lazy evaluation works in R. Is this used only to evaluate function arguments? Because I understand, for example,

f <- function(x = x, y = x*2) { c(x, y) } f(2) [1] 2 4 

But in other languages, for example. Haskell, lazy evaluation means that a function call is evaluated only when it has ever been used. So I expect something like this to start instantly:

 g <- function(x) { y <- sample(1:100000000) return(x) } g(4) 

But it explicitly evaluates the call to sample , although its result is not used.

Can someone explain how this works, or point me in the direction where this is explained in detail?

Related questions:

A question with a similar wording, but another problem

+6
source share
1 answer

As you can see, R does not use lazy bounds in the general sense. But R provides this functionality, if you need it, with the delayedAssign() function, as shown below:

 > system.time(y <- sample(1E8)) user system elapsed 7.636 0.128 7.766 > system.time(length(y)) user system elapsed 0 0 0 system.time(delayedAssign("x", sample(1E8))) user system elapsed 0.000 0.000 0.001 > system.time(length(x)) user system elapsed 7.680 0.096 7.777 

As you can see, y is evaluated immediately, so no time is needed to determine the length of y . x , on the other hand, is not evaluated when it is created, only the promise to evaluate x returned by delayedAssign() , and only when we really need the value of x , in this case, to determine its length, x .

It doesn’t matter if the expression is placed in the function or executed in the global environment, therefore, encapsulating the expression inside the function that you did in your example actually does not add anything, so I excluded it, But if you want to be sure, try:

 af <- function(z) { delayedAssign("x", sample(1E8)); return(z+1) } system.time(af(0)) user system elapsed 0 0 0 
+7
source

Source: https://habr.com/ru/post/1015606/


All Articles