[R] scope of a function + lazy evaluation

Duncan Murdoch murdoch.duncan at gmail.com
Mon May 10 12:41:29 CEST 2010


sayan dasgupta wrote:
> Hey guys,
>
> I have a doubt here , It is something simple I guess, what am I missing out
> here ??
>
>
> f <- function(y) function() y
> tmp <- vector("list", 5)
> for (i in 1:5) tmp[[i]] <- f(i)
> tmp[[1]]() # returns 5;
>
> z <- f(6)
> tmp[[1]]() # still returns 5; it should return 6 "ideally" right ???
>   

No, each time you call f you create a new y variable in its local 
evaluation frame.  So all 6 of your y variables are different.  However, 
the first 5 of them are all defined by the same expression, i.e. "i".  
Thus the first time they are evaluated they will each get the current 
value of that variable.  After the first evaluation, the value will be 
fixed, because that is when the value of y is forced.  So for example,

 > f <- function(y) function() y
 > tmp <- vector("list", 5)
 > for (i in 1:5) tmp[[i]] <- f(i)
 > tmp[[1]]() # returns 5;
[1] 5
 >
 > i <- 10
 > tmp[[2]]()
[1] 10
 > tmp[[1]]()
[1] 5

> Even if  I dont evaluate the function tmp[[1]] before i.e I do
> rm(list=ls())
> f <- function(y) function() y
> tmp <- vector("list", 5)
> for (i in 1:5) tmp[[i]] <- f(i)
>  z <- f(6)
> tmp[[1]]() # it still returns 5; it should return 6 "ideally" right ???
>   

See above.

Duncan Murdoch
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list