Binding a function to a list

Where am I going to miss something?

FUN<-list() make.FUN<-function(i) function(n) i+n for (i in 1:3) FUN[[i]]<-make.FUN(i) FUN[[1]](1) 

If I check the assignment of FUN, I get a link to a nested function (as expected):

 > FUN [[1]] function (n) i + n <environment: 0x03adfad0> [[2]] function (n) i + n <environment: 0x03ae0834> [[3]] function (n) i + n <environment: 0x03ae0604> > 

The problem is that if I check:

 > FUN[[1]](1) [1] 4 > 

when i expect 2! (obviously this overwrites the last value)

On the other hand, if I manually assign for each list item:

 FUN[[1]]<-make.FUN(1) FUN[[2]]<-make.FUN(2) FUN[[3]]<-make.FUN(3) 

I get the correct answer:

 > FUN[[1]](1) [1] 2 > FUN[[2]](3) [1] 5 > 

I could use do.call in a workaround, but I cannot figure out what the interpreter takes in the first loop, or why do.call is mandatory in this case. When I try:

 FUN<-list() make.FUN<-function(i) function(n) i+n for (i in 1:3) FUN[[i]]<-do.call('make.FUN',list(i)) 

I get (as expected):

 > FUN[[1]](2) [1] 3 

Any clue? (this only happens when using lists)

+4
source share
1 answer

Your question is almost a copy of the force example from the document. You need to do:

 FUN <- list() make.FUN <- function(i) { force(i); function(n) i+n } for (i in 1:3) FUN[[i]] <- make.FUN(i) FUN[[1]](1) # [1] 2 

Relevant parts from ?force :

force forces one to evaluate a formal argument. This can be useful if the argument is fixed in the closure using lexical rules for determining the scope and is later changed by explicit purpose or implicit purpose in the application loop or function.

+4
source

Source: https://habr.com/ru/post/1480036/


All Articles