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 m
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)
Hi,
it is sort of a bug (and sort of not a bug). You are getting bitten
by lazy evaluation. The value of y is not getting evaluated until
the second function is created and returned.
f <- function(y) {
y
g <- function(x) x + y
g
}
will give the behavior you want and I think there is
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