Skip to content
Prev 164075 / 398506 Next

lazy evaluation and scoping ?

I think actually it's both lazy evaluation and scoping. Here is how I
understand it.

Consider:
Now the RHS of the assignment is a function that returns the value of i.
That is:
function()i
<environment: 0x04e3af4c>

[[2]]
function()i
<environment: 0x04e3ae18>

So the question is: what will be the value of i when the function is
invoked? By R's lexical scoping rules it will be the value of i in the
enclosing environment of the function, which is the value of i in the
environment when the function is **defined** . This will be i = 2, the last
value of the for loop on exit. This is due to lazy evaluation -- the value
of i is not needed until the for() ends, as one can find by:
$i
[1] 2

$i
[1] 2

Hence one gets the results you originally saw. Adding the force(i) statement
forces i to be evaluated separately at each iteration of the loop, thus
placing the current values of i at each iteration into each function's
enclosing environment.

HTH.

-- Bert Gunter 

 

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Antonio, Fabio Di Narzo
Sent: Saturday, December 06, 2008 7:28 PM
To: Gabor Grothendieck
Cc: r-help at r-project.org
Subject: Re: [R] unexpected scoping behavior with functions created in a
loop

2008/12/6 Gabor Grothendieck <ggrothendieck at gmail.com>:
Tnx! That works! Sometimes lazy evaluation + side effects is just too
much (complicated) for me:D

bests,
a.
http://www.R-project.org/posting-guide.html