Hi, I wanted to create a list of closures. When I use Map(), mapply(), lapply(), etc., to create this list, it appears that the wrong arguments are being passed to the main function. For example: Main function:> adder <- function(x) function(y) x + yCreating list of closures with Map():> plus <- Map(adder,c(one=1,two=2))> plus$one(1)[1] 3> plus$two(1)[1] 3Examining what value was bound to "x":> Map(function(fn) get("x",environment(fn)),plus)$one[1] 2$two[1] 2This is what I had expected:> plus <- list(one=adder(1),two=adder(2))> plus$one(1)[1] 2> plus$two(1)[1] 3 > Map(function(fn) get("x",environment(fn)),plus)$one[1] 1$two[1] 2Anyone know what's going on? Thanks much! Stephen [[alternative HTML version deleted]]
On Thu, Aug 26, 2010 at 12:04 AM, Stephen T. <obsessively at hotmail.com> wrote:> > Hi, I wanted to create a list of closures. When I use Map(), mapply(), lapply(), etc., to create this list, it appears that the wrong arguments are being passed to the main function. For example: > Main function: >> adder <- function(x) function(y) x + y > Creating list of closures with Map(): >> plus <- Map(adder,c(one=1,two=2))> plus$one(1)[1] 3> plus$two(1)[1] 3 > Examining what value was bound to "x": >> Map(function(fn) get("x",environment(fn)),plus)$one[1] 2$two[1] 2 > > This is what I had expected: >> plus <- list(one=adder(1),two=adder(2))> plus$one(1)[1] 2> plus$two(1)[1] 3 >> Map(function(fn) get("x",environment(fn)),plus)$one[1] 1$two[1] 2 > > Anyone know what's going on? Thanks much!R uses lazy evaluation of function arguments. Try forcing x:> adder <- function(x) { force(x); function(y) x + y } > plus <- Map(adder,c(one=1,two=2)) > plus$one(1)[1] 2> plus$two(1)[1] 3
Maybe Matching Threads
- Re: [PATCH libnbd v2 2/5] lib: Implement closure lifetimes.
- [LLVMdev] Implementing closures and continuations
- Re: [PATCH libnbd 2/3] lib: Implement closure lifetimes.
- merging environments
- Re: [PATCH libnbd v2] generator: Define new Closure type instead of callbacks.