[R] Lexical scoping question

Luke Tierney luke at stat.uiowa.edu
Fri Feb 28 23:56:02 CET 2003


On Fri, 28 Feb 2003, Thomas Lumley wrote:

> On Fri, 28 Feb 2003, Jim Rogers wrote:
> 
> > Hello,
> >
> > Could someone please tell me what I am thinking about incorrectly:
> >
> > f <- function(y) {
> >   g <- function(x) x + y
> >   g
> > }
> >
> > In the following, I get what I expect based on my understanding of
> > lexical scoping:
> >
> > (f(1))(3) # 4
> > (f(2))(3) # 5
> >
> > But now,
> >
> > fs <- lapply(c(1, 2), f)
> > fs[[1]](3) # 5  (Why not 4 ?)
> > fs[[2]](3) # 5
> >
> >
> > Checking the environments of these functions, I see that "y" is indeed
> > bound to the value 2 in both cases:
> >
> > es <- lapply(fs, environment)
> > ys <- lapply(es, function(env) get("y", env)) # list(2, 2)
> >
> 
> Because that's the way it works.  It's a wart caused by the
> interaction of lazy evaluation and lexical scoping.  The problem is that
> `y' is not evaluated until you actually call an element of fs.

I'd call it a three-way interaction of lazy evaluation. lexical
scoping and changing variable bindings by explicit assignment by the
implicit assignment done in a loop.  The internal lapply actually does
something a bit different but with the same effect.  If the value of a
variable in a deferred evaluation is going to change and you want the
result of the evaluation befoe the change, then you have to force the
evaluation to occur before the change.

> You can do
> 
> 
>   force<-function(z) z
> 
>  f <- function(y) {
>    force(y)
>    g <- function(x) x + y
>    g
>  }
> 
> which will work as you expect.  IIRC Luke Tierney has added force() to
> the forthcoming R1.7.0.

It has been added now.

luke

-- 
Luke Tierney
University of Iowa                  Phone:             319-335-3386
Department of Statistics and        Fax:               319-335-3017
   Actuarial Science
241 Schaeffer Hall                  email:      luke at stat.uiowa.edu
Iowa City, IA 52242                 WWW:  http://www.stat.uiowa.edu




More information about the R-help mailing list