[R] scope of a function + lazy evaluation
Gabor Grothendieck
ggrothendieck at gmail.com
Mon May 10 12:48:38 CEST 2010
When you call a function R passes a "promise" to it for each argument.
A promise consists of the unevaluated variable together with the
environment in which it should evaluate the variable when time comes
to evaluate it. Thus tmp[[1]] contains function(y) y and in the
environment of function(y) y there is a promise y to evaluate i the
first time that y is actually used. When you write tmp[[1]]() the
promise is evaluated and since i is 5 at the point that is what you
get. If f had actually used y when it was called then you would have
gotten 1.
On Mon, May 10, 2010 at 6:06 AM, sayan dasgupta <kittudg at gmail.com> 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 ???
>
> 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 ???
>
> [[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