[R] scope of a function + lazy evaluation

Patrick Burns pburns at pburns.seanet.com
Mon May 10 12:14:29 CEST 2010


You are missing 'force'.

See 'The R Inferno' page 90.

In this case you can define:

f <- function(y) { force(y); function() y}


On 10/05/2010 11:06, 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 ???
>
> 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.
>

-- 
Patrick Burns
pburns at pburns.seanet.com
http://www.burns-stat.com
(home of 'Some hints for the R beginner'
and 'The R Inferno')



More information about the R-help mailing list